Skip to content

Commit dc347e1

Browse files
authored
refactor: reduce use of web3-* packages (#12373)
Co-authored-by: Jack-Works <Jack-Works@users.noreply.github.com>
1 parent e16e53e commit dc347e1

File tree

77 files changed

+278
-675
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+278
-675
lines changed

.vscode/settings.json

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
{
2-
"typescript.tsdk": "node_modules/typescript/lib",
3-
"typescript.preferences.importModuleSpecifierEnding": "js",
4-
"typescript.experimental.useTsgo": true,
2+
"js/ts.tsdk.path": "node_modules/typescript/lib",
3+
"js/ts.preferences.importModuleSpecifierEnding": "js",
4+
// https://github.com/microsoft/typescript-go/issues/2780
5+
"js/ts.experimental.useTsgo": false,
56
"js/ts.implicitProjectConfig.module": "NodeNext",
67
"js/ts.implicitProjectConfig.target": "ESNext",
78
"editor.formatOnSave": true,

eslint.config.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,12 @@ const moduleSystemRules = {
465465
message: 'Avoid using type unsafe methods.',
466466
importNames: ['get'],
467467
},
468+
{
469+
name: 'viem',
470+
message:
471+
'Use toHex from @masknet/shared-base. They have different behaviors on "0x-" strings. If you want to use the original toHex, import it like import { toHex as viem_toHex } from "viem".',
472+
importNames: ['toHex'],
473+
},
468474
{
469475
name: 'react-use',
470476
importNames: ['useLocalStorage'],

packages/mask/background/services/helper/firefly.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export async function encrypt(plainText: string, cryptoKey: string): Promise<str
7474
)
7575

7676
const hex = toHex(new Uint8Array(encryptedBuffer))
77-
return hex.startsWith('0x') ? hex.slice(2) : hex
77+
return hex.slice(2)
7878
}
7979

8080
export interface DesktopLinkInfoResponse {

packages/mask/background/services/wallet/services/legacyWallet.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ async function makePrivateKey(record: LegacyWalletRecord) {
4545
record._private_key_ ?
4646
await recoverWalletFromPrivateKey(record._private_key_)
4747
: await recoverWalletFromMnemonicWords(record.mnemonic, record.passphrase, record.path)
48-
return `0x${toHex(privateKey)}`
48+
return toHex(privateKey)
4949
}
5050

5151
async function recoverWalletFromMnemonicWords(
@@ -64,7 +64,7 @@ async function recoverWalletFromMnemonicWords(
6464
address: wallet_ts.EthereumAddress.from(walletPublicKey).address,
6565
privateKey: walletPrivateKey,
6666
privateKeyValid: true,
67-
privateKeyInHex: `0x${toHex(walletPrivateKey)}`,
67+
privateKeyInHex: toHex(walletPrivateKey),
6868
path,
6969
mnemonic,
7070
passphrase,

packages/mask/background/services/wallet/services/wallet/index.ts

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import * as bip39 from 'bip39'
22
import { first, last, omit } from 'lodash-es'
3-
import defer * as web3_utils from 'web3-utils'
43
import { toBytes } from '@ethereumjs/util'
54
import { api } from '@dimensiondev/mask-wallet-core/proto'
65
import { Signer } from '@masknet/web3-providers'
7-
import { ImportSource, type SignMessage, type Wallet } from '@masknet/shared-base'
6+
import { ImportSource, toHex, type SignMessage, type Wallet } from '@masknet/shared-base'
87
import { HD_PATH_WITHOUT_INDEX_ETHEREUM } from '@masknet/web3-shared-base'
98
import * as Mask from '../maskwallet/index.js'
109
import * as database from './database/index.js'
1110
import * as password from './password.js'
11+
import { keccak256 } from 'viem'
1212

1313
const MAX_DERIVE_COUNT = 99
1414

@@ -60,9 +60,7 @@ export async function createMnemonicWords() {
6060
}
6161

6262
export async function createMnemonicId(mnemonic: string) {
63-
const id = web3_utils.sha3(mnemonic)
64-
if (!id) throw new Error('Failed to create mnemonic id.')
65-
return id
63+
return keccak256(toHex(mnemonic))
6664
}
6765

6866
export async function getPrimaryWalletByMnemonicId(mnemonicId?: string) {

packages/mask/content-script/site-adaptors/twitter.com/collecting/post.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import { memoize } from 'lodash-es'
2-
import defer * as web3_utils from 'web3-utils'
32
import { IntervalWatcher } from '@dimensiondev/holoflows-kit'
43
import type { PostInfo } from '@masknet/plugin-infra/content-script'
5-
import { EnhanceableSite, PostIdentifier, ProfileIdentifier } from '@masknet/shared-base'
4+
import { EnhanceableSite, PostIdentifier, ProfileIdentifier, toHex } from '@masknet/shared-base'
65
import {
76
FlattenTypedMessage,
87
extractTextFromTypedMessage,
@@ -29,6 +28,7 @@ import {
2928
toastLinkSelector,
3029
} from '../utils/selector.js'
3130
import { IdentityProviderTwitter } from './identity.js'
31+
import { keccak256 } from 'viem'
3232

3333
function getParentTweetNode(node: HTMLElement) {
3434
return node.closest<HTMLElement>('[data-testid="tweet"]')
@@ -122,7 +122,7 @@ function registerPostCollectorInner(
122122
const tweetNode = getTweetNode(node)
123123
const parentTweetNode = isQuotedTweet(tweetNode) ? getParentTweetNode(tweetNode!) : null
124124
if (!tweetNode || shouldSkipDecrypt(node, tweetNode)) {
125-
return `keccak256:${web3_utils.keccak256(node.innerText)}`
125+
return `keccak256:${keccak256(toHex(node.innerText))}`
126126
}
127127
const parentTweetId = parentTweetNode ? getPostId(parentTweetNode) : ''
128128
const tweetId = getPostId(tweetNode)

packages/mask/content-script/site-adaptors/twitter.com/utils/fetch.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import defer * as web3_utils from 'web3-utils'
21
import { flattenDeep } from 'lodash-es'
32
import { normalizeImageURL, parseId } from './url.js'
43
import {
@@ -16,6 +15,8 @@ import {
1615
} from '@masknet/typed-message'
1716
import { collectNodeText, collectTwitterEmoji } from '../../../utils/index.js'
1817
import { IMAGE_RENDER_IGNORE } from '../customization/render-fragments.js'
18+
import { keccak256 } from 'viem'
19+
import { toHex } from '@masknet/shared-base'
1920

2021
/**
2122
* Get post id from dom, including normal tweet, quoted tweet and retweet one
@@ -38,9 +39,9 @@ export function getPostId(node: HTMLElement) {
3839
} else if (timeNode) {
3940
// Quoted tweet in timeline has no a status link to detail page,
4041
// so use the timestamp as post id instead
41-
pid = `timestamp-keccak256:${web3_utils.keccak256(timeNode.getAttribute('datetime')!)}`
42+
pid = `timestamp-keccak256:${keccak256(toHex(timeNode.getAttribute('datetime')!))}`
4243
} else {
43-
pid = `keccak256:${web3_utils.keccak256(node.innerText)}`
44+
pid = `keccak256:${keccak256(toHex(node.innerText))}`
4445
}
4546

4647
// You can't retweet a tweet or a retweet, but only cancel retweeting

packages/mask/dashboard/pages/CreateMaskWallet/AddDeriveWallet/index.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,10 @@ import urlcat from 'urlcat'
33
import { memo, useCallback, useMemo, useState } from 'react'
44
import { useAsyncFn } from 'react-use'
55
import { useLocation, useNavigate } from 'react-router-dom'
6-
import defer * as web3_utils from 'web3-utils'
76
import { useQueries, useQuery } from '@tanstack/react-query'
87
import { delay } from '@masknet/kit'
98
import { DeriveWalletTable } from '@masknet/shared'
10-
import { DashboardRoutes, EMPTY_LIST } from '@masknet/shared-base'
9+
import { DashboardRoutes, EMPTY_LIST, toHex } from '@masknet/shared-base'
1110
import { makeStyles } from '@masknet/theme'
1211
import { useWallet, useWallets } from '@masknet/web3-hooks-base'
1312
import { EVMWeb3 } from '@masknet/web3-providers'
@@ -28,6 +27,7 @@ import { SetupFrameController } from '../../../components/SetupFrame/index.js'
2827
import { ResetWalletContext } from '../context.js'
2928
import Services from '#services'
3029
import { Trans } from '@lingui/react/macro'
30+
import { keccak256 } from 'viem'
3131

3232
const useStyles = makeStyles()((theme) => ({
3333
header: {
@@ -85,7 +85,7 @@ export const Component = memo(function AddDeriveWallet() {
8585

8686
const { mnemonic, password, isReset } = state
8787
// Avoid leaking mnemonic to react-query
88-
const mnemonicHash = web3_utils.sha3(mnemonic)
88+
const mnemonicHash = keccak256(toHex(mnemonic))
8989
const [pathIndexes, setPathIndexes] = useState<number[]>([])
9090
const { handlePasswordAndWallets } = ResetWalletContext.useContainer()
9191

packages/mask/popups/pages/Wallet/GasSetting/GasSetting1559.tsx

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,13 @@ import { useNavigate } from 'react-router-dom'
44
import { Controller, useForm } from 'react-hook-form'
55
import { isEmpty } from 'lodash-es'
66
import { z as zod } from 'zod'
7-
import defer * as web3_utils from 'web3-utils'
87
import { BigNumber } from 'bignumber.js'
98
import { makeStyles } from '@masknet/theme'
109
import { formatGweiToEther, formatGweiToWei, formatWeiToEther, formatWeiToGwei } from '@masknet/web3-shared-evm'
1110
import { zodResolver } from '@hookform/resolvers/zod'
1211
import { Typography } from '@mui/material'
1312
import { LoadingButton } from '@mui/lab'
14-
import { NetworkPluginID, PopupRoutes, NUMERIC_INPUT_REGEXP_PATTERN } from '@masknet/shared-base'
13+
import { NetworkPluginID, PopupRoutes, NUMERIC_INPUT_REGEXP_PATTERN, toHex } from '@masknet/shared-base'
1514
import {
1615
formatCurrency,
1716
GasOptionType,
@@ -31,6 +30,7 @@ import { StyledInput } from '../../../components/StyledInput/index.js'
3130
import Services from '#services'
3231
import { FormattedCurrency } from '@masknet/shared'
3332
import { Trans, useLingui } from '@lingui/react/macro'
33+
import { formatGwei } from 'viem'
3434

3535
const useStyles = makeStyles()((theme) => ({
3636
options: {
@@ -236,9 +236,9 @@ export const GasSetting1559 = memo(() => {
236236
if (value.formatterTransaction._tx.maxFeePerGas && value.formatterTransaction._tx.maxPriorityFeePerGas) {
237237
setValue(
238238
'maxPriorityFeePerGas',
239-
web3_utils.fromWei(toFixed(value.formatterTransaction._tx.maxPriorityFeePerGas), 'gwei'),
239+
formatGwei(BigInt(toFixed(value.formatterTransaction._tx.maxPriorityFeePerGas))),
240240
)
241-
setValue('maxFeePerGas', web3_utils.fromWei(toFixed(value.formatterTransaction._tx.maxFeePerGas), 'gwei'))
241+
setValue('maxFeePerGas', formatGwei(BigInt(toFixed(value.formatterTransaction._tx.maxFeePerGas))))
242242
} else {
243243
setOption(1)
244244
}
@@ -268,9 +268,9 @@ export const GasSetting1559 = memo(() => {
268268
param === 'latest' ? param : (
269269
{
270270
...Object(param),
271-
gas: web3_utils.toHex(new BigNumber(data.gasLimit).toString()),
272-
maxPriorityFeePerGas: web3_utils.toHex(formatGweiToWei(data.maxPriorityFeePerGas).toFixed(0)),
273-
maxFeePerGas: web3_utils.toHex(formatGweiToWei(data.maxFeePerGas).toFixed(0)),
271+
gas: toHex(data.gasLimit),
272+
maxPriorityFeePerGas: toHex(formatGweiToWei(data.maxPriorityFeePerGas).toFixed(0)),
273+
maxFeePerGas: toHex(formatGweiToWei(data.maxFeePerGas).toFixed(0)),
274274
}
275275
),
276276
)

packages/mask/popups/pages/Wallet/GasSetting/Prior1559GasSetting.tsx

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ import { Controller, useForm } from 'react-hook-form'
44
import { useNavigate } from 'react-router-dom'
55
import { BigNumber } from 'bignumber.js'
66
import { isEmpty } from 'lodash-es'
7-
import defer * as web3_utils from 'web3-utils'
87
import { z as zod } from 'zod'
98
import { zodResolver } from '@hookform/resolvers/zod'
10-
import { NetworkPluginID, NUMERIC_INPUT_REGEXP_PATTERN, PopupRoutes } from '@masknet/shared-base'
9+
import { NetworkPluginID, NUMERIC_INPUT_REGEXP_PATTERN, PopupRoutes, toHex } from '@masknet/shared-base'
1110
import { Typography } from '@mui/material'
1211
import { LoadingButton } from '@mui/lab'
1312
import { useChainContext, useGasOptions, useNativeToken, useNativeTokenPrice } from '@masknet/web3-hooks-base'
@@ -228,8 +227,8 @@ export const Prior1559GasSetting = memo(() => {
228227
if (!value) return
229228
const config = value.payload.params!.map((param) => ({
230229
...Object(param),
231-
gas: web3_utils.toHex(new BigNumber(data.gasLimit).toString()),
232-
gasPrice: web3_utils.toHex(formatGweiToWei(data.gasPrice).toString()),
230+
gas: toHex(data.gasLimit),
231+
gasPrice: toHex(formatGweiToWei(data.gasPrice).toFixed(0)),
233232
}))
234233
await Services.Wallet.updateUnconfirmedRequest({
235234
...value.payload,

0 commit comments

Comments
 (0)