Skip to content

Commit

Permalink
fix: bugfix for popup swap page (#10503)
Browse files Browse the repository at this point in the history
  • Loading branch information
nuanyang233 committed Aug 20, 2023
1 parent d11aafa commit bfe45d1
Show file tree
Hide file tree
Showing 20 changed files with 82 additions and 48 deletions.
6 changes: 3 additions & 3 deletions packages/dashboard/src/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@
"transfer_cost": "Cost {{gasFee}} {{symbol}} ≈ ${{usd}}",
"done": "Done",
"labs": "D.Market",
"onboarding_wallet": "wallet",
"wallet_transactions_pending": "Pending",
"wallet_recovery_title": "Recover your wallet",
"wallet_select_address": "Select Address",
Expand Down Expand Up @@ -417,8 +418,7 @@
"create_wallet_payment_password_place_holder": "At least 6 charachters",
"create_wallet_re_enter_payment_password": "Confirm Payment Password",
"create_wallet_payment_password_tip_1": "Payment Password should be between 6 and 20 characters.",
"create_wallet_payment_password_tip_2": "Your wallet data will be encrypted using this payment password, which will also be required for trade confirmation and wallet unlocking.",
"create_wallet_payment_password_tip_3": "The payment password is securely stored on your device. We do not have the capability to retrieve it, so it is essential that you remember it.",
"create_wallet_payment_password_tip_2": "Your payment password encrypts wallet data and is needed for trade confirmations and unlocking. It's securely stored on your device, and we cannot retrieve it. Please remember it.",
"create_wallet_your_wallet_address": "Your wallet address",
"create_wallet_key_store_not_support": "Unsupported key store data",
"create_wallet_key_store_password": "Keystore password",
Expand Down Expand Up @@ -451,7 +451,7 @@
"file_reselect": "Reselect",
"mobile_number": "Mobile number",
"persona_phrase_title": "Persona Recovery Phrase",
"persona_phrase_tips": "Please select the correct method to restore the backup.",
"persona_phrase_tips": "12-word recovery phrase are used to recovery your persona data.",
"persona_phrase_copy_description": "The mnemonic has been copied, please keep it in a safe place.",
"persona_phrase_create_tips": "Never share 12-word secret recovery phrase with anyone!",
"persona_phrase_create_check_tips": "I wrote down the words in the correct order",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,6 @@ const CreateWalletForm = memo(function CreateWalletForm() {
</Box>

<Typography className={classes.tipsBottom}>{t.create_wallet_payment_password_tip_2()}</Typography>
<Typography className={classes.tipsBottom}>{t.create_wallet_payment_password_tip_3()}</Typography>
</form>
<SetupFrameController>
<PrimaryButton
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ const Onboarding = memo(function Onboarding() {
return [
<Typography key="identity">
{t.create_wallet_onboarding_creating_identity()}
{t.wallet()}
{t.onboarding_wallet()}
</Typography>,
<Typography key="account">
{t.create_wallet_onboarding_generating_accounts()}
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/shared-ui/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -1074,7 +1074,7 @@
"popups_backup_password_tips": "Please set up backup password to export private key.",
"popups_backup_password_inconsistency": "The two entered passwords are inconsistent.",
"popups_backup_password_incorrect": "Incorrect password.",
"popups_backup_password_invalid": "Password must be between 8 to 20",
"popups_backup_password_invalid": "Please enter backup password to export persona private key.",
"popups_backup_password_set_successfully": "Backup password set successfully",
"popups_export_private_key_tips": "This export is only for exporting private key. We do not export any other data. If you need more data, please go to Settings: <a> Global Backup </a>",
"popups_export_json_file_tips": "This file has been encrypted and stored with your current password. Your current password is needed to decrypt this file when using it to import wallet.",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ export const ConnectedWallet = memo<ConnectedWalletProps>(function ConnectedWall
result.createdAt,
{ signature },
)

// Broadcast updates.
MaskMessages.events.ownProofChanged.sendToAll()
showSnackbar(t('popups_wallet_disconnect_success'))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ const ConnectWalletPage = memo(function ConnectWalletPage() {
const result = await bindProof(payload, walletSignature, personaSignature)

if (result) showSnackbar(t('popups_verify_wallet_sign_success_tips'))

// Broadcast updates
MaskMessages.events.ownProofChanged.sendToAll()
return true
Expand Down
33 changes: 32 additions & 1 deletion packages/mask/src/extension/popups/pages/Swap/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo } from 'react'
import { useEffect, useMemo } from 'react'
import { AllProviderTradeContext } from '@masknet/plugin-trader'
import { Appearance } from '@masknet/public-api'
import { SharedContextProvider } from '@masknet/shared'
Expand All @@ -10,6 +10,9 @@ import { useSwapPageTheme } from '../../../../utils/theme/useSwapPageTheme.js'
import { NetworkSelector } from '../../components/NetworkSelector/index.js'
import { useTokenParams } from '../../hook/useTokenParams.js'
import { SwapBox } from './SwapBox/index.js'
import { SiteAdaptorContextRef } from '@masknet/plugin-infra/dom'
import { TwitterAdaptor } from '../../../../../shared/site-adaptors/implementations/twitter.com.js'
import { openWindow } from '@masknet/shared-base-ui'

const useStyles = makeStyles()((theme) => {
return {
Expand Down Expand Up @@ -66,6 +69,34 @@ export default function SwapPage() {
applyMaskColorVars(document.body, Appearance.light)
const chainContextValue = useMemo(() => ({ chainId }), [chainId])

useEffect(() => {
SiteAdaptorContextRef.value = {
...SiteAdaptorContextRef.value,
share(text) {
const url = TwitterAdaptor.getShareLinkURL!(text)
const width = 700
const height = 520
const openedWindow = openWindow(url, 'share', {
width,
height,
screenX: window.screenX + (window.innerWidth - width) / 2,
screenY: window.screenY + (window.innerHeight - height) / 2,
opener: true,
referrer: true,
behaviors: {
toolbar: true,
status: true,
resizable: true,
scrollbars: true,
},
})
if (openedWindow === null) {
location.assign(url)
}
},
}
}, [])

return (
<ThemeProvider theme={theme}>
<SharedContextProvider>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,7 @@ const AssetItem = memo(function AssetItem({ asset, onItemClick, ...rest }: Asset
secondaryTypographyProps={{ component: 'div' }}
secondary={
<ProgressiveText className={classes.balance} loading={balance.pending} skeletonWidth={60}>
{balance.value}
{asset.symbol}
{balance.value} {asset.symbol}
</ProgressiveText>
}>
<TextOverflowTooltip title={asset.name}>
Expand Down
1 change: 1 addition & 0 deletions packages/plugins/Trader/src/SiteAdaptor/trader/Trader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ export const Trader = forwardRef<TraderRef, TraderProps>((props: TraderProps, re
focusedTrade={focusedTrade}
gasPrice={gasPrice}
onSwap={onSwap}
refresh={() => allTradeComputed.map((x) => x.retry())}
/>
</>
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export interface TradeStateBarProps {
inputTokenBalance?: string
gasPrice?: string
onSwap: () => void
refresh: () => void
}
export function TraderStateBar({
trades,
Expand All @@ -71,6 +72,7 @@ export function TraderStateBar({
inputTokenBalance,
gasPrice,
onSwap,
refresh,
}: TradeStateBarProps) {
const t = useI18N()
const { classes } = useStyles()
Expand Down Expand Up @@ -202,7 +204,8 @@ export function TraderStateBar({
color: 'primary',
style: { borderRadius: 8 },
size: 'medium',
}}>
}}
callback={refresh}>
<ChainBoundary expectedChainId={chainId} expectedPluginID={pluginID}>
<TokenSecurityBoundary
tokenInfo={{
Expand Down
5 changes: 0 additions & 5 deletions packages/plugins/Trader/src/trader/0x/useTradeCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,8 @@ import { Web3 } from '@masknet/web3-providers'
import { useChainContext, useNetworkContext } from '@masknet/web3-hooks-base'
import type { SwapQuoteResponse, TradeComputed } from '../../types/index.js'
import { SUPPORTED_CHAIN_ID_LIST } from './constants.js'
import { useSwapErrorCallback } from '../../SiteAdaptor/trader/hooks/useSwapErrorCallback.js'

export function useTradeCallback(tradeComputed: TradeComputed<SwapQuoteResponse> | null, gasConfig?: GasConfig) {
const notifyError = useSwapErrorCallback()
const { account, chainId } = useChainContext<NetworkPluginID.PLUGIN_EVM>()
const { pluginID } = useNetworkContext()

Expand Down Expand Up @@ -55,9 +53,6 @@ export function useTradeCallback(tradeComputed: TradeComputed<SwapQuoteResponse>
if (!receipt?.status) return
return receipt?.transactionHash
} catch (error: unknown) {
if (error instanceof Error) {
notifyError(error.message)
}
return
}
}, [account, chainId, stringify(config), gasConfig, pluginID])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,13 @@ import { Web3 } from '@masknet/web3-providers'
import { SLIPPAGE_DEFAULT } from '../../constants/index.js'
import { type SwapResponse, type TradeComputed, TradeStrategy } from '../../types/index.js'
import { useTradeAmount } from './useTradeAmount.js'
import { useSwapErrorCallback } from '../../SiteAdaptor/trader/hooks/useSwapErrorCallback.js'

export function useTradeCallback(
trade: TradeComputed<SwapResponse> | null,
exchangeProxyContract: ExchangeProxy | null,
allowedSlippage = SLIPPAGE_DEFAULT,
gasConfig?: GasConfig,
) {
const notifyError = useSwapErrorCallback()
const { account, chainId } = useChainContext<NetworkPluginID.PLUGIN_EVM>()
const { pluginID } = useNetworkContext()
const Others = useWeb3Others()
Expand Down Expand Up @@ -98,10 +96,7 @@ export function useTradeCallback(
if (!receipt?.status) return
return receipt?.transactionHash
} catch (error) {
if (error instanceof Error) {
notifyError(error.message)
}
return
}
}, [chainId, trade, tradeAmount, exchangeProxyContract, BALANCER_ETH_ADDRESS, pluginID, notifyError, Others])
}, [chainId, trade, tradeAmount, exchangeProxyContract, BALANCER_ETH_ADDRESS, pluginID, Others])
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ import type { GasConfig } from '@masknet/web3-shared-evm'
import { Web3 } from '@masknet/web3-providers'
import { PluginTraderRPC } from '../../messages.js'
import type { SwapBancorRequest, TradeComputed } from '../../types/index.js'
import { useSwapErrorCallback } from '../../SiteAdaptor/trader/hooks/useSwapErrorCallback.js'

export function useTradeCallback(tradeComputed: TradeComputed<SwapBancorRequest> | null, gasConfig?: GasConfig) {
const notifyError = useSwapErrorCallback()
const { pluginID } = useNetworkContext()
const { account, chainId } = useChainContext<NetworkPluginID.PLUGIN_EVM>()

Expand Down Expand Up @@ -55,10 +53,7 @@ export function useTradeCallback(tradeComputed: TradeComputed<SwapBancorRequest>

return receipt?.transactionHash
} catch (error) {
if (error instanceof Error) {
notifyError(error.message)
}
return
}
}, [account, chainId, stringify(trade), gasConfig, pluginID, notifyError])
}, [account, chainId, stringify(trade), gasConfig, pluginID])
}
7 changes: 1 addition & 6 deletions packages/plugins/Trader/src/trader/dodo/useTradeCallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ import { NetworkPluginID } from '@masknet/shared-base'
import type { GasConfig, Transaction } from '@masknet/web3-shared-evm'
import { Web3 } from '@masknet/web3-providers'
import type { SwapRouteSuccessResponse, TradeComputed } from '../../types/index.js'
import { useSwapErrorCallback } from '../../SiteAdaptor/trader/hooks/useSwapErrorCallback.js'

export function useTradeCallback(tradeComputed: TradeComputed<SwapRouteSuccessResponse> | null, gasConfig?: GasConfig) {
const notifyError = useSwapErrorCallback()
const { account, chainId } = useChainContext<NetworkPluginID.PLUGIN_EVM>()
const { pluginID } = useNetworkContext()

Expand Down Expand Up @@ -42,10 +40,7 @@ export function useTradeCallback(tradeComputed: TradeComputed<SwapRouteSuccessRe
const receipt = await Web3.confirmTransaction(hash, { chainId })
return receipt.transactionHash
} catch (error) {
if (error instanceof Error) {
notifyError(error.message)
}
return
}
}, [account, chainId, stringify(config), gasConfig, pluginID, notifyError])
}, [account, chainId, stringify(config), gasConfig, pluginID])
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,8 @@ import type { GasConfig, Transaction } from '@masknet/web3-shared-evm'
import { useChainContext, useNetworkContext } from '@masknet/web3-hooks-base'
import { Web3 } from '@masknet/web3-providers'
import type { SwapOOSuccessResponse, TradeComputed } from '../../types/index.js'
import { useSwapErrorCallback } from '../../SiteAdaptor/trader/hooks/useSwapErrorCallback.js'

export function useTradeCallback(tradeComputed: TradeComputed<SwapOOSuccessResponse> | null, gasConfig?: GasConfig) {
const notifyError = useSwapErrorCallback()
const { account, chainId } = useChainContext<NetworkPluginID.PLUGIN_EVM>()
const { pluginID } = useNetworkContext()

Expand Down Expand Up @@ -44,10 +42,7 @@ export function useTradeCallback(tradeComputed: TradeComputed<SwapOOSuccessRespo
if (!receipt?.status) return
return receipt?.transactionHash
} catch (error) {
if (error instanceof Error) {
notifyError(error.message)
}
return
}
}, [account, chainId, stringify(config), pluginID, notifyError])
}, [account, chainId, stringify(config), pluginID])
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export interface EthereumERC20TokenApprovedBoundaryProps extends withClasses<'bu
contractName?: string
showHelperToken?: boolean
failedContent?: React.ReactNode
callback?: () => void
}

export function EthereumERC20TokenApprovedBoundary(props: EthereumERC20TokenApprovedBoundaryProps) {
Expand All @@ -51,6 +52,7 @@ export function EthereumERC20TokenApprovedBoundary(props: EthereumERC20TokenAppr
contractName,
showHelperToken = true,
failedContent,
callback,
} = props

const t = useSharedI18N()
Expand All @@ -72,7 +74,16 @@ export function EthereumERC20TokenApprovedBoundary(props: EthereumERC20TokenAppr
)

const [{ type: approveStateType, allowance }, transactionState, approveCallback, _resetApproveCallback] =
useERC20TokenApproveCallback(token?.address ?? '', amount, spender ?? '', refetch, token?.chainId)
useERC20TokenApproveCallback(
token?.address ?? '',
amount,
spender ?? '',
() => {
callback?.()
refetch()
},
token?.chainId,
)

const loading = spendersLoading || approveStateType === ApproveStateType.UPDATING || transactionState.loadingApprove

Expand Down
8 changes: 7 additions & 1 deletion packages/shared/src/hooks/usePersonaProofs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { NextIDProof } from '@masknet/web3-providers'
import { EMPTY_LIST, type BindingProof, MaskMessages } from '@masknet/shared-base'
import { delay } from '@masknet/kit'

export function usePersonaProofs(publicKey?: string) {
const result = useQuery<BindingProof[], Error>({
Expand All @@ -16,7 +17,12 @@ export function usePersonaProofs(publicKey?: string) {

useEffect(
() =>
MaskMessages.events.ownProofChanged.on(() => {
MaskMessages.events.ownProofChanged.on(async () => {
// Clearing the query cache when the proof relation changes
if (publicKey) {
await NextIDProof.clearPersonaQueryCache(publicKey)
await delay(2000)
}
refetch()
}),
[publicKey],
Expand Down
4 changes: 4 additions & 0 deletions packages/theme/src/Theme/component-changes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
linearProgressClasses,
selectClasses,
filledInputClasses,
formHelperTextClasses,
} from '@mui/material'
import type { MaskColor } from './colors.js'

Expand Down Expand Up @@ -916,6 +917,9 @@ export const TextField = (mode: PaletteMode, colors: MaskColor) => ({
[`& .${filledInputClasses.root}`]: {
borderRadius: 8,
},
[`& .${formHelperTextClasses.root}`]: {
marginLeft: 0,
},
},
},
},
Expand Down
13 changes: 7 additions & 6 deletions packages/web3-providers/src/NextID/proof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
createBindingProofFromProfileQuery,
EMPTY_LIST,
getDomainSystem,
Sniffings,
} from '@masknet/shared-base'
import { env } from '@masknet/flags'
import { PROOF_BASE_URL_DEV, PROOF_BASE_URL_PROD, RELATION_SERVICE_URL } from './constants.js'
Expand Down Expand Up @@ -227,6 +226,12 @@ export class NextIDProofAPI implements NextIDBaseAPI.Proof {
return fetchCachedJSON<T>(request, init)
}

async clearPersonaQueryCache(personaPublicKey: string) {
const url = getPersonaQueryURL(NextIDPlatform.NextID, personaPublicKey)
await staleNextIDCached(url)
return
}

async bindProof(
uuid: string,
personaPublicKey: string,
Expand Down Expand Up @@ -273,11 +278,7 @@ export class NextIDProofAPI implements NextIDBaseAPI.Proof {

async queryExistedBindingByPersona(personaPublicKey: string) {
const url = getPersonaQueryURL(NextIDPlatform.NextID, personaPublicKey)
/**
* Because popup and background share memory, caching often causes queries to be updated late.
* Since popups don't have a lot of queries in them, the cache is cleared before each request
*/
if (Sniffings.is_popup_page) await staleNextIDCached(url)

const { ids } = await this.fetchFromProofService<NextIDBindings>(url)
// Will have only one item when query by personaPublicKey
return first(ids)
Expand Down

0 comments on commit bfe45d1

Please sign in to comment.