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

fix: bugfix for lens super follow #9236

Merged
merged 4 commits into from
Apr 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { memo, useContext } from 'react'
import { makeStyles } from '@masknet/theme'
import { Box, Typography } from '@mui/material'
import { Icons } from '@masknet/icons'
import { useNavigate, useLocation, useMatch } from 'react-router-dom'
import { useNavigate, useLocation } from 'react-router-dom'
import { PageTitleContext } from '../../context.js'
import { PopupRoutes } from '@masknet/shared-base'

Expand Down Expand Up @@ -68,7 +68,6 @@ export const NormalHeader = memo<NormalHeaderProps>(({ onlyTitle, onClose }) =>

const showClose = location.pathname === PopupRoutes.ConnectWallet && !goBack

const matchDeleteWallet = useMatch(PopupRoutes.DeleteWallet)
if (onlyTitle)
return (
<Box className={classes.container} style={{ justifyContent: 'center' }}>
Expand All @@ -90,7 +89,6 @@ export const NormalHeader = memo<NormalHeaderProps>(({ onlyTitle, onClose }) =>
className={classes.container}
style={{
justifyContent: showTitle ? 'center' : 'flex-start',
...(matchDeleteWallet ? { fixed: 0, position: 'fixed', width: '100%', top: 0 } : {}),
}}>
{showTitle ? (
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { memo, useCallback, useMemo, useState } from 'react'
import { Trans } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import { useContainer } from 'unstated-next'
import { Button, Typography } from '@mui/material'
import { Box, Button, Typography } from '@mui/material'
import { makeStyles } from '@masknet/theme'
import { Icons } from '@masknet/icons'
import { formatEthereumAddress } from '@masknet/web3-shared-evm'
Expand Down Expand Up @@ -120,7 +120,7 @@ const DeleteWallet = memo(() => {
useTitle(t('popups_delete_wallet'))

return (
<>
<Box style={{ maxHeight: 502, overflowY: 'auto' }}>
<div className={classes.content}>
<div className={classes.warning}>
<Icons.Warning size={48} />
Expand Down Expand Up @@ -173,7 +173,7 @@ const DeleteWallet = memo(() => {
{t('delete')}
</Button>
</div>
</>
</Box>
)
})

Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
import { Icons } from '@masknet/icons'
import { InjectedDialog, WalletConnectedBoundary } from '@masknet/shared'
import {
ChainBoundary,
EthereumERC20TokenApprovedBoundary,
InjectedDialog,
WalletConnectedBoundary,
} from '@masknet/shared'
import { CrossIsolationMessages, NetworkPluginID } from '@masknet/shared-base'
import { useRemoteControlledDialog } from '@masknet/shared-base-ui'
import { ActionButton, makeStyles } from '@masknet/theme'
import { useChainContext, useFungibleTokenBalance, useWallet } from '@masknet/web3-hooks-base'
import { useChainContext, useFungibleTokenBalance, useNetworkContext, useWallet } from '@masknet/web3-hooks-base'
import { Lens } from '@masknet/web3-providers'
import { FollowModuleType } from '@masknet/web3-providers/types'
import { formatBalance, isLessThan, resolveIPFS_URL } from '@masknet/web3-shared-base'
import { ChainId } from '@masknet/web3-shared-evm'
import { formatBalance, isLessThan, resolveIPFS_URL, ZERO } from '@masknet/web3-shared-base'
import { ChainId, createERC20Token, formatAmount, ProviderType } from '@masknet/web3-shared-evm'
import { Avatar, Box, Button, buttonClasses, CircularProgress, DialogContent, Typography } from '@mui/material'
import { first } from 'lodash-es'
import { useMemo, useState } from 'react'
Expand Down Expand Up @@ -87,8 +92,8 @@ export function FollowLensDialog() {
const [handle, setHandle] = useState('')
const { classes } = useStyles()
const wallet = useWallet()
const { account, chainId } = useChainContext()

const { account, chainId, providerType } = useChainContext<NetworkPluginID.PLUGIN_EVM>()
const { pluginID } = useNetworkContext()
const { open, closeDialog } = useRemoteControlledDialog(
CrossIsolationMessages.events.followLensDialogEvent,
(ev) => {
Expand Down Expand Up @@ -139,6 +144,18 @@ export function FollowLensDialog() {
}, [profile, defaultProfile])
// #endregion

const approved = useMemo(() => {
if (!profile?.followModule?.amount?.asset) return { amount: ZERO.toFixed() }
const { address, name, symbol, decimals } = profile.followModule.amount.asset
const token = createERC20Token(chainId, address, name, symbol, decimals)
const amount = formatAmount(profile.followModule.amount.value, decimals)

return {
token,
amount,
}
}, [profile?.followModule?.amount, chainId])

// #region follow and unfollow event handler
const [{ loading: followLoading }, handleFollow] = useFollow(profile?.id, followModule, !!defaultProfile, retry)
const [{ loading: unfollowLoading }, handleUnfollow] = useUnfollow(profile?.id, retry)
Expand All @@ -152,7 +169,8 @@ export function FollowLensDialog() {
const disabled = useMemo(() => {
if (
!!wallet?.owner ||
chainId !== ChainId.Matic ||
pluginID !== NetworkPluginID.PLUGIN_EVM ||
providerType === ProviderType.Fortmatic ||
followLoading ||
unfollowLoading ||
(profile?.followModule?.type === FollowModuleType.ProfileFollowModule && !defaultProfile) ||
Expand All @@ -166,8 +184,9 @@ export function FollowLensDialog() {
profile?.followModule?.type === FollowModuleType.RevertFollowModule
)
return true

return false
}, [wallet?.owner, chainId, followLoading, unfollowLoading, feeTokenBalance, profile?.followModule])
}, [wallet?.owner, chainId, followLoading, unfollowLoading, feeTokenBalance, profile?.followModule, pluginID])

const [element] = useHover((isHovering) => {
const getButtonText = () => {
Expand All @@ -186,20 +205,44 @@ export function FollowLensDialog() {
return t.follow()
}
return (
<ActionButton
variant="roundedContained"
className={classes.followAction}
disabled={disabled}
loading={followLoading || unfollowLoading || loading}
onClick={isFollowing ? handleUnfollow : handleFollow}>
{getButtonText()}
</ActionButton>
<EthereumERC20TokenApprovedBoundary
spender={value?.profile.followModule?.contractAddress}
amount={approved.amount}
token={approved.token}
showHelperToken={false}
ActionButtonProps={{
variant: 'roundedContained',
className: classes.followAction,
}}
infiniteUnlockContent={t.unlock_token_tips({
value: value?.profile.followModule?.amount?.value ?? ZERO.toFixed(),
symbol: approved.token?.symbol ?? '',
})}>
<ChainBoundary
expectedPluginID={pluginID}
expectedChainId={ChainId.Matic}
ActionButtonPromiseProps={{
variant: 'roundedContained',
className: classes.followAction,
startIcon: null,
}}
switchText={t.switch_network_tips()}>
<ActionButton
variant="roundedContained"
className={classes.followAction}
disabled={disabled}
loading={followLoading || unfollowLoading || loading}
onClick={isFollowing ? handleUnfollow : handleFollow}>
{getButtonText()}
</ActionButton>
</ChainBoundary>
</EthereumERC20TokenApprovedBoundary>
)
})

const tips = useMemo(() => {
if (wallet?.owner) return t.follow_wallet_tips()
else if (chainId !== ChainId.Matic) return t.follow_chain_tips()
if (wallet?.owner || pluginID !== NetworkPluginID.PLUGIN_EVM || providerType === ProviderType.Fortmatic)
return t.follow_wallet_tips()
else if (profile?.followModule?.type === FollowModuleType.ProfileFollowModule && !defaultProfile)
return t.follow_with_profile_tips()
else if (
Expand All @@ -217,7 +260,7 @@ export function FollowLensDialog() {
return t.follow_gas_tips()
}
return
}, [wallet?.owner, chainId, profile, feeTokenBalance])
}, [wallet?.owner, chainId, profile, feeTokenBalance, pluginID, providerType])

const avatar = useMemo(() => {
if (!profile?.picture?.original) return
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useChainContext, useWeb3Connection } from '@masknet/web3-hooks-base'
import { Lens } from '@masknet/web3-providers'
import { ChainId } from '@masknet/web3-shared-evm'
import { ChainId, isValidAddress } from '@masknet/web3-shared-evm'
import isBefore from 'date-fns/isBefore'
import add from 'date-fns/add'
import { useAsyncFn } from 'react-use'
Expand All @@ -11,17 +11,21 @@ export function useQueryAuthenticate(address: string) {
const connection = useWeb3Connection()

return useAsyncFn(async () => {
if (!address || !connection || chainId !== ChainId.Matic) return

if (storage.accessToken?.value?.token && isBefore(new Date(), storage.accessToken.value.expireDate)) {
return storage.accessToken.value.token
} else if (storage.refreshToken?.value?.token && isBefore(new Date(), storage.refreshToken.value.expireDate)) {
const authenticate = await Lens.refresh(storage.refreshToken.value.token)
if (!address || !connection || chainId !== ChainId.Matic || !isValidAddress(address)) return

const accessToken = storage.accessToken?.value?.[address]
const refreshToken = storage.refreshToken?.value?.[address]
if (accessToken && isBefore(new Date(), accessToken.expireDate)) {
return accessToken.token
} else if (refreshToken && isBefore(new Date(), refreshToken.expireDate)) {
const authenticate = await Lens.refresh(refreshToken.token)
if (!authenticate) return
// Only reset accessToken
await storage.accessToken?.setValue({
token: authenticate.accessToken,
expireDate: add(new Date(), { minutes: 30 }),
[address]: {
token: authenticate.accessToken,
expireDate: add(new Date(), { minutes: 30 }),
},
})
return authenticate.accessToken
}
Expand All @@ -40,13 +44,17 @@ export function useQueryAuthenticate(address: string) {
*/

await storage.accessToken?.setValue({
token: authenticate.accessToken,
expireDate: add(new Date(), { minutes: 30 }),
[address]: {
token: authenticate.accessToken,
expireDate: add(new Date(), { minutes: 30 }),
},
})

await storage.refreshToken?.setValue({
token: authenticate.refreshToken,
expireDate: add(new Date(), { days: 7 }),
[address]: {
token: authenticate.refreshToken,
expireDate: add(new Date(), { days: 7 }),
},
})

return authenticate.accessToken
Expand Down
6 changes: 5 additions & 1 deletion packages/plugins/Web3Profile/src/SNSAdaptor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { useAsync } from 'react-use'
import { NextIDProof } from '@masknet/web3-providers'
import { LensBadge } from './components/LensBadge.js'
import { LensPopup } from './components/LensPopup.js'
import { ChainContextProvider } from '@masknet/web3-hooks-base'
import { ChainId } from '@masknet/web3-shared-evm'

const sns: Plugin.SNSAdaptor.Definition = {
...base,
Expand All @@ -25,7 +27,9 @@ const sns: Plugin.SNSAdaptor.Definition = {
return (
<SNSAdaptorContext.Provider value={context}>
<Web3ProfileDialog />
<FollowLensDialog />
<ChainContextProvider value={{ chainId: ChainId.Matic }}>
<FollowLensDialog />
</ChainContextProvider>
<LensPopup />
</SNSAdaptorContext.Provider>
)
Expand Down
22 changes: 14 additions & 8 deletions packages/plugins/Web3Profile/src/SNSAdaptor/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,20 @@ export interface UnlistedConfig {
}

export interface LensTokenStorageType {
accessToken?: {
token: string
expireDate: Date
}
refreshToken?: {
token: string
expireDate: Date
}
accessToken?: Record<
string,
{
token: string
expireDate: Date
}
>
refreshToken?: Record<
string,
{
token: string
expireDate: Date
}
>
}

/**
Expand Down
3 changes: 2 additions & 1 deletion packages/plugins/Web3Profile/src/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@
"follow_with_charge_tips": "No enough balance to complete follow process.",
"follow_with_revert_tips": "This user has banned follow function.",
"follow_wallet_tips": "Current wallet does not support to interact with Lens protocol.",
"follow_chain_tips": "Current chain does not support to interact with Lens protocol. Please switch to Polygon.",
"follow_gas_tips": "Need to pay gas fee to follow this account.",
"unlock_token_tips": "Unlock {{value}} {{symbol}} and follow",
"switch_network_tips": "Switch to Polygon and Follow",
"plugin_wallet_disconnect": "Disconnect",
"wallet_status_button_change": "Change",
"plugin_wallet_on_connect": "Connect Wallet",
Expand Down
28 changes: 19 additions & 9 deletions packages/shared/src/UI/components/ChainBoundary/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
useAllowTestnet,
useWeb3State,
useChainIdValid,
useProviderDescriptor,
ActualChainContextProvider,
} from '@masknet/web3-hooks-base'
import type { Web3Helper } from '@masknet/web3-helpers'
Expand All @@ -18,9 +17,10 @@ import { WalletIcon } from '../WalletIcon/index.js'
import { type ActionButtonPromiseProps } from '../ActionButton/index.js'
import { Icons } from '@masknet/icons'
import type { NetworkPluginID } from '@masknet/shared-base'
import { useActivatedPlugin } from '@masknet/plugin-infra/dom'
import { useSharedI18N } from '../../../locales/index.js'
import { WalletMessages } from '@masknet/plugin-wallet'
import { useAsyncFn } from 'react-use'
import { delay } from '@masknet/kit'

const useStyles = makeStyles()((theme) => ({
tooltip: {
Expand Down Expand Up @@ -52,6 +52,7 @@ export interface ChainBoundaryProps<T extends NetworkPluginID> extends withClass
children?: React.ReactNode
ActionButtonPromiseProps?: Partial<ActionButtonPromiseProps>
actualNetworkPluginID?: T
switchText?: string
}

export function ChainBoundaryWithoutContext<T extends NetworkPluginID>(props: ChainBoundaryProps<T>) {
Expand All @@ -60,6 +61,7 @@ export function ChainBoundaryWithoutContext<T extends NetworkPluginID>(props: Ch
expectedChainId,
expectedAccount,
actualNetworkPluginID,
switchText,
forceShowingWrongNetworkButton = false,
predicate = (actualPluginID, actualChainId) =>
actualPluginID === expectedPluginID && actualChainId === expectedChainId,
Expand All @@ -69,18 +71,14 @@ export function ChainBoundaryWithoutContext<T extends NetworkPluginID>(props: Ch
const { classes } = useStyles(undefined, { props })

const { pluginID: actualPluginID } = useNetworkContext(actualNetworkPluginID)
const plugin = useActivatedPlugin(actualPluginID, 'any')
const expectedPlugin = useActivatedPlugin(expectedPluginID, 'any')

const { Others: actualOthers } = useWeb3State(actualPluginID)
const { Others: actualOthers, Connection } = useWeb3State(actualPluginID)

const {
account,
chainId: actualChainId,
providerType: actualProviderType,
} = useChainContext({ account: expectedAccount })
const actualProviderDescriptor = useProviderDescriptor(actualPluginID)
const actualChainName = actualOthers?.chainResolver.chainName(actualChainId)

const { Others: expectedOthers } = useWeb3State(expectedPluginID)
const expectedAllowTestnet = useAllowTestnet(expectedPluginID)
Expand All @@ -105,6 +103,17 @@ export function ChainBoundaryWithoutContext<T extends NetworkPluginID>(props: Ch
})
}, [expectedNetworkDescriptor])

const [{ loading }, onSwitchChain] = useAsyncFn(async () => {
if (actualProviderType !== ProviderType.WalletConnect || isMatched || !expectedChainAllowed) return
const connection = Connection?.getConnection?.()
if (!connection) return

await connection.switchChain?.(expectedChainId)
await delay(1500)

return 'complete'
}, [expectedChainAllowed, isMatched, expectedChainId, actualProviderType, Connection])

const renderBox = (children?: React.ReactNode, tips?: string) => {
return (
<ShadowRootTooltip title={tips ?? ''} classes={{ tooltip: classes.tooltip }} arrow placement="top">
Expand Down Expand Up @@ -181,11 +190,12 @@ export function ChainBoundaryWithoutContext<T extends NetworkPluginID>(props: Ch
size={18}
/>
}
disabled
onClick={onSwitchChain}
loading={loading}
className={classes.switchButton}
sx={props.ActionButtonPromiseProps?.sx}
{...props.ActionButtonPromiseProps}>
{t.plugin_wallet_switch_network({ network: expectedChainName ?? '' })}
{switchText ?? t.plugin_wallet_switch_network({ network: expectedChainName ?? '' })}
</ActionButton>,
t.plugin_wallet_connect_tips(),
)
Expand Down