Skip to content

Commit

Permalink
fix: bugfix for local backup (#10850)
Browse files Browse the repository at this point in the history
  • Loading branch information
nuanyang233 committed Sep 25, 2023
1 parent 2abe173 commit 222986c
Show file tree
Hide file tree
Showing 21 changed files with 89 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ export async function exportKeyStoreJSON(address: string, unverifiedPassword?: s
const masterPassword = await password.INTERNAL_getMasterPasswordRequired()
const wallet = await database.getWalletRequired(address)
if (!wallet.storedKeyInfo) throw new Error(`Cannot export private key of ${address}.`)

const exported =
wallet.derivationPath && !wallet.configurable
? await Mask.exportKeyStoreJSONOfPath({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const BackupInfoCard = memo(function BackupInfoCard({ info }: BackupInfoP
operations={<Typography className={classes.desc}>{formatFileSize(info.size, true)}</Typography>}>
{Number.isNaN(info.uploadedAt) ? null : (
<Typography fontSize={12} color="second">
{formatDateTime(fromUnixTime(info.uploadedAt), 'yyyy-MM-dd hh:mm')}
{formatDateTime(fromUnixTime(info.uploadedAt), 'yyyy-MM-dd HH:mm')}
</Typography>
)}
</FileFrame>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export const ConfirmBackupInfo = memo(function ConfirmBackupInfo() {
</PrimaryButton>,
)
}, [handleNext, t, loading])
console.log(backupFileInfo)

if (!backupFileInfo) return null

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export const RestoreWalletFromLocal = memo(function RestorePersonaFromLocal({
{!readingFile ? (
<Box mt={4}>
<PasswordField
fullWidth
placeholder={t.create_wallet_key_store_password()}
type="password"
onChange={(e) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/dashboard/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@
"data_backup_title": "Select the contents of the backup",
"data_backup_description": "Please select the appropriate method to restore your personal data.",
"cloud_backup_title": "login to your Mask Cloud",
"cloud_backup_backup_exists": "You used <strong>{{account}}</strong> for the last cloud backup..",
"cloud_backup_backup_exists": "You used <strong>{{account}}</strong> for the last cloud backup.",
"cloud_backup_no_exist_tips": "Please use your frequently used email account or mobile phone for backup.",
"cloud_backup_email_title": "E-mail",
"cloud_backup_phone_title": "Mobile",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export const BackupPreviewDialog = memo<BackupPreviewDialogProps>(function Backu
render={({ field }) => (
<PasswordField
{...field}
onFocus={() => clearErrors()}
onFocus={() => clearErrors('backupPassword')}
sx={{ mb: 2 }}
placeholder={t.settings_label_backup_password()}
error={!!errors.backupPassword?.message}
Expand All @@ -212,7 +212,7 @@ export const BackupPreviewDialog = memo<BackupPreviewDialogProps>(function Backu
render={({ field }) => (
<PasswordField
{...field}
onFocus={() => clearErrors()}
onFocus={() => clearErrors('paymentPassword')}
sx={{ mb: 2 }}
placeholder={t.sign_in_account_local_backup_payment_password()}
error={!!errors.paymentPassword?.message}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { memo, useMemo } from 'react'
import { Box, formHelperTextClasses, Typography } from '@mui/material'
import { makeStyles, MaskColorVar } from '@masknet/theme'
import { Box, Typography } from '@mui/material'
import { makeStyles } from '@masknet/theme'
import { z as zod } from 'zod'
import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
Expand Down Expand Up @@ -35,16 +35,6 @@ const useStyles = makeStyles()((theme) => ({
width: '100%',
marginTop: 10,
},
textField: {
padding: theme.spacing(1),
fontSize: 12,
lineHeight: '16px',
borderRadius: 6,
[`&.${formHelperTextClasses.error}`]: {
boxShadow: `0 0 0 ${theme.spacing(0.5)} ${MaskColorVar.redMain.alpha(0.2)}`,
border: `1px solid ${MaskColorVar.redMain.alpha(0.8)}`,
},
},
tips: {
fontSize: 14,
lineHeight: '18px',
Expand Down Expand Up @@ -140,7 +130,6 @@ const CreateWalletForm = memo(function CreateWalletForm() {
placeholder={t.create_wallet_payment_password_place_holder()}
error={!isValid && !!errors.password?.message}
helperText={!isValid ? errors.password?.message : ''}
InputProps={{ className: classes.textField }}
/>
)}
name="password"
Expand All @@ -153,7 +142,6 @@ const CreateWalletForm = memo(function CreateWalletForm() {
error={!isValid && !!errors.confirm?.message}
helperText={!isValid ? errors.confirm?.message : ''}
placeholder={t.create_wallet_re_enter_payment_password()}
InputProps={{ className: classes.textField }}
/>
)}
name="confirm"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ const useStyles = makeStyles()((theme) => ({

export const CloudBackupPreview = memo(function CloudBackupPreview() {
const t = useDashboardI18N()

const { classes, theme, cx } = useStyles()

const [params] = useSearchParams()
const location = useLocation()

Expand Down Expand Up @@ -149,9 +151,15 @@ export const CloudBackupPreview = memo(function CloudBackupPreview() {
</Box>
<Box className={classes.content}>
<Icons.Message size={48} />
<Box flex={1}>
<Box width="clamp(188px, 27%, 35%)" flex={1}>
<TextOverflowTooltip title={previewInfo.abstract} arrow placement="top">
<Typography className={classes.text}>{previewInfo.abstract}</Typography>
<Typography
className={classes.text}
whiteSpace="nowrap"
textOverflow="ellipsis"
overflow="hidden">
{previewInfo.abstract}
</Typography>
</TextOverflowTooltip>

<Typography display="flex" columnGap="4px">
Expand All @@ -170,22 +178,25 @@ export const CloudBackupPreview = memo(function CloudBackupPreview() {
</Typography>
</Typography>
</Box>
<ActionButton
startIcon={<Icons.Cloud size={18} />}
color="primary"
className={classes.button}
loading={mergeLoading}
onClick={handleMergeClick}>
{t.cloud_backup_merge_local_data()}
</ActionButton>
<ActionButton
loading={overwriteLoading}
onClick={handleOverwriteClick}
startIcon={<Icons.CloudBackup2 size={18} />}
color="error"
className={cx(classes.button)}>
{t.cloud_backup_overwrite_backup()}
</ActionButton>

<Box display="flex" justifyContent="flex-end" flex={1} columnGap={1} minWidth={436}>
<ActionButton
startIcon={<Icons.Cloud size={18} />}
color="primary"
className={classes.button}
loading={mergeLoading}
onClick={handleMergeClick}>
{t.cloud_backup_merge_local_data()}
</ActionButton>
<ActionButton
loading={overwriteLoading}
onClick={handleOverwriteClick}
startIcon={<Icons.CloudBackup2 size={18} />}
color="error"
className={cx(classes.button)}>
{t.cloud_backup_overwrite_backup()}
</ActionButton>
</Box>
</Box>
</>
) : (
Expand Down
2 changes: 2 additions & 0 deletions packages/mask/shared-ui/locales/en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
"coming_soon": "Coming soon",
"max": "Max",
"data": "Data",
"redpacket_a_token": "a token",
"redpacket_an_nft": "an NFT",
"available_balance": "Available Balance",
"available_amount": "{{- amount}} available",
"failed_to_transfer_token": "Failed to transfer token: {{- message}}",
Expand Down
4 changes: 2 additions & 2 deletions packages/mask/shared-ui/locales/zh-CN.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"promote": ":performancing_arts::performancing_arts::performancing_arts: 是否早已厌倦了纯文字信息?您可以尝试发送加密信息给朋友。安装Mask.io来发送您第一个加密推文吧。",
"promote_red_packet": "🧧🧧🧧 尝试给你的好友发送代币或 NFTs 红包,分享此时的喜悦吧! 安装 Mask.io 发送你的第一个红包",
"promote_red_packet": "我刚刚用 Mask Network 插件在 Twitter 上创建一个 {{token}} 红包。欢迎抽取和转发",
"promote_file_service": "📃📃📃 尝试在推特上使用永久的、去中心化的文件存储功能。安装 Mask.io 上传并分享你的第一份永久的去中心化存储文件,由主流去中心化存储方案提供技术支持。",
"promote_savings": "Hi朋友们,我刚刚在 {{chain}} 上质押了 {{amount}} {{symbol}} 。关注@{{account}} 来查找更多的质押项目。",
"promote_withdraw": "Hi朋友们,我刚刚在 {{chain}} 上质押了 {{- amount}} {{symbol}} 。关注@{{account}} 来查找更多的质押项目。",
Expand Down Expand Up @@ -92,7 +92,7 @@
"application_settings_tab_plug_app-unlisted-placeholder": "点击应用图标将会在应用列表中显示。",
"persona_load_failed": "加载失败",
"additional_post_box__encrypted_post_pre": "安装 #mask_io 解密此贴文 ! {{encrypted}}",
"additional_post_box__encrypted_post_pre_red_packet_sns_official_account": "使用 #mask_io 来领取这个红包!@{{account}} \n\n$t(promote_red_packet)\n {{encrypted}}",
"additional_post_box__encrypted_post_pre_red_packet_sns_official_account": "$t(promote_red_packet) 关注@{{account}},获取更多 Web3 应用的最新资讯和洞见。 \n\n🧧🧧🧧 尝试用 Mask.io 给你的好友发送红包。\n\n {{encrypted}}",
"additional_post_box__encrypted_post_pre_red_packet": "使用 #mask_io 来认领这个红包!@{{encrypted}}",
"additional_post_box__encrypted_post_pre_file_service_sns_official_account": "$t(promote_file_service)\n {{encrypted}}",
"additional_post_box__encrypted_post_pre_file_service": "$t(promote_file_service) {{encrypted}}",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ function decorateEncryptedText(encrypted: string, t: I18NFunction, meta?: Meta):
? t('additional_post_box__encrypted_post_pre_red_packet_sns_official_account', {
encrypted,
account: officialAccount,
token: meta?.has(`${PluginID.RedPacket}:1`) ? 'a token' : 'an NFT',
token: meta?.has(`${PluginID.RedPacket}:1`) ? t('redpacket_a_token') : t('redpacket_an_nft'),
})
: t('additional_post_box__encrypted_post_pre_red_packet', { encrypted })
} else if (meta?.has(`${PluginID.FileService}:3`)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const useStyles = makeStyles()((theme) => ({
background: theme.palette.maskColor.secondaryBottom,
padding: theme.spacing(2),
boxShadow: theme.palette.maskColor.bottomBg,
backdropFilter: 'blur(8px)',
left: 0,
right: 0,
display: 'flex',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,22 @@
import { memo, useRef, type ReactNode, useEffect } from 'react'
import { Icons } from '@masknet/icons'
import { TextOverflowTooltip, makeStyles } from '@masknet/theme'
import { Box, Drawer, Typography } from '@mui/material'
import { Box, Drawer, Typography, backdropClasses } from '@mui/material'

const useStyles = makeStyles()((theme) => ({
root: {
paper: {
padding: theme.spacing(2.25),
borderRadius: '24px 24px 0 0',
background: theme.palette.maskColor.bottom,
},
root: {
[`& .${backdropClasses.root}`]: {
background:
theme.palette.mode === 'dark'
? 'rgba(255, 255, 255, 0.10)'
: 'linear-gradient(0deg, rgba(0, 0, 0, 0.40) 0%, rgba(0, 0, 0, 0.40) 100%), rgba(28, 104, 243, 0.20)',
backdropFilter: 'blur(5px)',
},
},
header: {
display: 'flex',
Expand Down Expand Up @@ -47,7 +57,11 @@ export const BottomDrawer = memo<BottomDrawerProps>(function BottomDrawer({ open
if (open) everOpenRef.current = true
}, [open])
return (
<Drawer anchor="bottom" onClose={handleClose} open={open} classes={{ paper: classes.root }}>
<Drawer
anchor="bottom"
onClose={handleClose}
open={open}
classes={{ paper: classes.paper, root: classes.root }}>
<Box className={classes.header}>
<TextOverflowTooltip title={title}>
<Typography className={classes.title}>{title}</Typography>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,6 @@ export const ChangeBackupPasswordModal = memo<ActionModalBaseProps>(function Cha
[handleSubmit, updateUser, showSnackbar],
)

console.log(errors.oldPassword?.type)
return (
<ActionModal
header={t('popups_settings_change_backup_password')}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,10 @@ function WalletRemoveDrawer({ wallet, error, password, setPassword, setError, ..
if (!remainWallets.includes(nextWallet)) nextWallet = remainWallets[0]

await Web3.removeWallet?.(wallet.address, password, { providerType: ProviderType.MaskWallet })

await Web3.connect({
providerType: ProviderType.MaskWallet,
account: nextWallet.address,
account: nextWallet?.address ?? '',
})
rest.onClose?.()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,18 @@ const ExportPrivateKey = memo(function ExportPrivateKey() {
if (!wallet?.address) return
const now = formatDateTime(Date.now(), 'yyyy-MM-dd')
const jsonFile = await Services.Wallet.exportKeyStoreJSON(wallet.address, state?.password)
// TODO: The address parameter should be returned by the sdk and not displayed as such. We need to wait for the sdk to be upgraded.
await saveFileFromBuffer({
fileContent: encodeText(JSON.stringify(jsonFile)),
fileContent: encodeText(
JSON.stringify({
...JSON.parse(jsonFile),
address: wallet.address.slice(2),
}),
),
fileName: `mask-network-keystore-backup-${now}.json`,
mimeType: MimeType.JSON,
})
}, [wallet?.address])
}, [wallet?.address, state?.password])

const { loading: getMnemonicLoading, value: mnemonic } = useAsync(async () => {
if (!wallet) return
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
formatEthereumAddress,
ChainId,
ErrorEditor,
addGasMargin,
} from '@masknet/web3-shared-evm'
import { toHex, toUtf8 } from 'web3-utils'
import { useNavigate, useSearchParams } from 'react-router-dom'
Expand Down Expand Up @@ -204,7 +205,7 @@ const Interaction = memo(function Interaction() {
return toHex(value)
})
: {}),

gas: toHex(addGasMargin(gasConfig?.gas ?? x.gas).toString()),
chainId: toHex(x.chainId),
nonce: toHex(x.nonce),
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,6 @@ export const PersonaSelectPanel = memo<PersonaSelectPanelProps>((props) => {
if (!isVerified && enableVerify) {
onClose?.()
ApplicationBoardModal.close()
if (finishTarget) {
CrossIsolationMessages.events.applicationDialogEvent.sendToLocal({
open: false,
pluginID: finishTarget,
})
}
await handleVerifyNextID(selectedPersona.persona, currentProfileIdentify.identifier?.userId)
if (!finishTarget) Telemetry.captureEvent(EventType.Access, EventID.EntryProfileConnectVerify)
else Telemetry.captureEvent(EventType.Access, EventID.EntryMaskComposeVerifyTwitter)
Expand Down
10 changes: 6 additions & 4 deletions packages/web3-providers/src/Web3/Base/state/Message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,13 @@ export class MessageState<Request, Response> implements Web3MessageState<Request
return message_
}

async applyAndWaitResponse(message: TransferableMessage<Request, Response>): Promise<Response> {
async applyAndWaitResponse(
message: TransferableMessage<Request, Response>,
): Promise<ReasonableMessage<Request, Response>> {
const { ID } = await this.applyRequest(message)
const { response } = await this.waitForApprovingRequest(ID)
if (!response) throw new Error('Invalid response')
return response
const reasonableMessage = await this.waitForApprovingRequest(ID)
if (!reasonableMessage.response) throw new Error('Invalid response')
return reasonableMessage
}

async updateMessage(id: string, updates: Partial<TransferableMessage<Request, Response>>): Promise<void> {
Expand Down
10 changes: 8 additions & 2 deletions packages/web3-providers/src/Web3/EVM/interceptors/Popups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,16 @@ export class Popups implements Middleware<ConnectionContext> {
}

if (!Web3StateRef.value.Message) throw new Error('Failed to approve request.')
const response = await Web3StateRef.value.Message.applyAndWaitResponse(request)
const { request: updates, response } = await Web3StateRef.value.Message.applyAndWaitResponse(request)

context.config = {
...context.config,
...updates.arguments.params[0],
}

const editor = ErrorEditor.from(null, response)

if (editor.presence) {
if (editor.presence || !response) {
context.abort(editor.error)
} else {
context.write(response.result)
Expand Down
4 changes: 3 additions & 1 deletion packages/web3-shared/base/src/specs/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1028,7 +1028,9 @@ export interface MessageState<Request, Response> extends Startable {
/** Applies a request. */
applyRequest(message: TransferableMessage<Request, Response>): Promise<ReasonableMessage<Request, Response>>
/** Applies a request and waits for confirmation from the user. */
applyAndWaitResponse<T>(message: TransferableMessage<Request, Response>): Promise<Response>
applyAndWaitResponse<T>(
message: TransferableMessage<Request, Response>,
): Promise<ReasonableMessage<Request, Response>>
/** Approves a request. */
approveRequest(id: string, updates?: Request): Promise<JsonRpcResponse | void>
/** Rejects a request. */
Expand Down

0 comments on commit 222986c

Please sign in to comment.