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

refactor: internalSend #8338

Merged
merged 20 commits into from Dec 27, 2022
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
1 change: 0 additions & 1 deletion packages/dashboard/src/API.tsx
Expand Up @@ -23,7 +23,6 @@ export interface PluginServices {
derivationPath?: string,
initialPassword?: string | undefined,
): Promise<string>
updateMaskAccount(options: { account?: string | undefined }): Promise<void>
resolveMaskAccount(accounts: MaskAccount[]): Promise<void>
verifyPassword(unverifiedPassword: string): Promise<boolean>
}
Expand Down
Expand Up @@ -108,23 +108,23 @@ const CreateMnemonic = memo(() => {
await PluginServices.Wallet.setPassword(password)
}

const address_ = await PluginServices.Wallet.recoverWalletFromMnemonic(
const address = await PluginServices.Wallet.recoverWalletFromMnemonic(
name,
words.join(' '),
`${HD_PATH_WITHOUT_INDEX_ETHEREUM}/0`,
)

await connection?.connect({
account: address_,
account: address,
chainId: ChainId.Mainnet,
})
await PluginServices.Wallet.resolveMaskAccount([
{
address: address_,
address,
},
])

return address_
return address
}, [location.search, words, resetCallback, hasPassword, searchParams, connection])

const onClose = useCallback(() => {
Expand Down
Expand Up @@ -17,7 +17,8 @@ export function useDeleteBound() {
platform as NextIDPlatform,
)
if (!payload) throw new Error('Failed to create persona payload.')
const signResult = await Services.Identity.generatePersonalSignResult(
const signResult = await Services.Identity.generateSignResult(
'message',
persona_.identifier,
payload.signPayload,
)
Expand Down
47 changes: 7 additions & 40 deletions packages/mask/background/services/identity/persona/sign.ts
@@ -1,6 +1,6 @@
import { v4 as uuid } from 'uuid'
import { keccakFromString, ecsign, bufferToHex, toRpcSig, privateToPublic, publicToAddress } from 'ethereumjs-util'
import { encodeText, timeout } from '@masknet/kit'
import { bufferToHex, privateToPublic, publicToAddress } from 'ethereumjs-util'
import { timeout } from '@masknet/kit'
import { personalSign } from '@metamask/eth-sig-util'
import type { Transaction } from '@masknet/web3-shared-evm'
import { Web3 } from '@masknet/web3-providers'
Expand Down Expand Up @@ -40,16 +40,7 @@ export async function signWithPersona<T>({
'Timeout',
)

switch (method) {
case 'eth':
return generateEthSignResult(signer, message as string)
case 'personal':
return generatePersonalSignResult(signer, message as string)
case 'transaction':
return generateTransactionSignResult(signer, message as Transaction)
default:
throw new Error(`Unknown sign method: ${method}.`)
}
return generateSignResult<T>(method, signer, message)
}

export async function generateSignResult<T>(
Expand All @@ -58,10 +49,8 @@ export async function generateSignResult<T>(
message: T,
): Promise<PersonaSignResult> {
switch (method) {
case 'eth':
return generateEthSignResult(signer, message as string)
case 'personal':
return generatePersonalSignResult(signer, message as string)
case 'message':
return generateMessageSignResult(signer, message as string)
case 'transaction':
return generateTransactionSignResult(signer, message as Transaction)
default:
Expand All @@ -70,12 +59,12 @@ export async function generateSignResult<T>(
}

/**
* Sign a raw message (eth sign)
* Sign a message in EVM way
* @param signer
* @param message
* @returns
*/
export async function generateEthSignResult(signer: ECKeyIdentifier, message: string) {
export async function generateMessageSignResult(signer: ECKeyIdentifier, message: string) {
const persona = (await queryPersonasWithPrivateKey()).find((x) => x.identifier === signer)
if (!persona) throw new Error('Persona not found')
const privateKey = Buffer.from(fromBase64URL(persona.privateKey.d!))
Expand All @@ -89,28 +78,6 @@ export async function generateEthSignResult(signer: ECKeyIdentifier, message: st
}
}

/**
* Sign as an EVM message (personal sign)
* @param signer
* @param message
* @returns
*/
export async function generatePersonalSignResult(signer: ECKeyIdentifier, message: string) {
const persona = (await queryPersonasWithPrivateKey()).find((x) => x.identifier === signer)
if (!persona) throw new Error('Persona not found')

const length = encodeText(message).length
const messageHash = keccakFromString(`\x19Ethereum Signed Message:\n${length}${message}`, 256)
const privateKey = Buffer.from(fromBase64URL(persona.privateKey.d!))
const signature = ecsign(messageHash, privateKey)

return {
persona: persona.identifier,
signature: toRpcSig(signature.v, signature.r, signature.s),
address: bufferToHex(publicToAddress(privateToPublic(privateKey))),
}
}

/**
* Sign an EVM transaction
* @param signer
Expand Down
3 changes: 2 additions & 1 deletion packages/mask/src/components/DataSource/useNextIDVerify.ts
Expand Up @@ -25,7 +25,8 @@ export function useNextIDVerify() {
languageSettings.value ?? 'default',
)
if (!payload) throw new Error('Failed to create persona payload.')
const signResult = await Services.Identity.generatePersonalSignResult(
const signResult = await Services.Identity.generateSignResult(
'message',
persona.identifier,
payload.signPayload,
)
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/src/extension/mask-sdk/bridge/index.ts
Expand Up @@ -5,7 +5,7 @@ import { SNSMethods } from './sns_context.js'
export const maskSDKServer: BridgeAPI = {
async persona_sign_web3(message) {
const result = await Services.Identity.signWithPersona({
method: 'personal',
method: 'message',
message: String(message),
})
return result.signature
Expand Down
Expand Up @@ -58,7 +58,8 @@ const AccountDetail = memo(() => {

if (!result) return

const signature = await Service.Identity.generatePersonalSignResult(
const signature = await Service.Identity.generateSignResult(
'message',
currentPersona.identifier,
result.signPayload,
)
Expand Down
Expand Up @@ -87,7 +87,8 @@ const ConnectedWallets = memo(() => {

if (!result) return

const signature = await Service.Identity.generatePersonalSignResult(
const signature = await Service.Identity.generateSignResult(
'message',
currentPersona.identifier,
result.signPayload,
)
Expand Down
@@ -1,4 +1,5 @@
import { memo, useEffect, useState } from 'react'
import { useAsyncFn } from 'react-use'
import { makeStyles } from '@masknet/theme'
import { Button, Typography } from '@mui/material'
import { MaskMessages, useI18N } from '../../../../../utils/index.js'
Expand All @@ -7,7 +8,6 @@ import { PersonaInformation, PopupRoutes } from '@masknet/shared-base'
import { usePersonasFromDB } from '../../../../../components/DataSource/usePersonasFromDB.js'
import { PersonaContext } from '../hooks/usePersonaContext.js'
import { MethodAfterPersonaSign } from '../../Wallet/type.js'
import { useAsyncFn } from 'react-use'
import Services from '../../../../service.js'
import { useTitle } from '../../../hook/useTitle.js'

Expand Down Expand Up @@ -120,7 +120,7 @@ const PersonaSignRequest = memo(() => {
switch (method) {
case MethodAfterPersonaSign.DISCONNECT_NEXT_ID:
if (!message) break
const signatureResult = await Services.Identity.generatePersonalSignResult(selectedPersona, message)
const signatureResult = await Services.Identity.generateSignResult('message', selectedPersona, message)

const profileIdentifier = url.get('profileIdentifier')
const platform = url.get('platform')
Expand Down
Expand Up @@ -88,7 +88,8 @@ const VerifyWallet = memo(() => {
const [{ value: signature }, personaSilentSign] = useAsyncFn(async () => {
if (!payload || !currentPersona?.identifier) return
try {
const signResult = await Services.Identity.generatePersonalSignResult(
const signResult = await Services.Identity.generateSignResult(
'message',
currentPersona.identifier,
payload.signPayload,
)
Expand Down
Expand Up @@ -113,7 +113,7 @@ const AddDeriveWallet = memo(() => {
`${HD_PATH_WITHOUT_INDEX_ETHEREUM}/${firstPath}`,
)

const wallets = await Promise.all(
await Promise.all(
unDeriveWallets
.slice(1)
.map(async (pathIndex) =>
Expand All @@ -126,7 +126,7 @@ const AddDeriveWallet = memo(() => {
)

if (!currentMaskWalletAccountSettings.value) {
connection?.connect({ account: firstWallet })
await connection?.connect({ account: firstWallet })
}
}
navigate(PopupRoutes.Wallet, { replace: true })
Expand Down
Expand Up @@ -79,7 +79,7 @@ const ConnectWalletPage = memo(() => {
) => {
if (provider.type === ProviderType.MaskWallet) {
const connection = Connection?.getConnection?.()
if (connection) connection.disconnect()
if (connection) await connection.disconnect()
if (isLocked && !getLockStatusLoading) {
navigate(urlcat(PopupRoutes.Unlock, { from: PopupRoutes.SelectWallet, goBack: true, popup: true }))
return
Expand Down
Expand Up @@ -111,7 +111,7 @@ const DeleteWallet = memo(() => {
try {
await Wallet?.removeWallet?.(wallet.address, password)

connection?.connect({
await connection?.connect({
account: first(Wallet?.wallets?.getCurrentValue())?.address ?? '',
})

Expand Down
Expand Up @@ -132,7 +132,7 @@ const SelectWallet = memo(() => {
}

const wallet = wallets.find((x) => isSameAddress(x.address, selected))
connection?.connect({
await connection?.connect({
// TODO: Just for test, will remove this logic
chainId: wallet?.owner ? ChainId.Mumbai : chainId,
account: selected,
Expand Down
Expand Up @@ -131,7 +131,7 @@ const WalletRecovery = memo(() => {

// Set default wallet
if (wallet) {
connection?.connect({
await connection?.connect({
account: wallet.address,
chainId: ChainId.Mainnet,
})
Expand Down
2 changes: 1 addition & 1 deletion packages/mask/src/plugins/NextID/hooks/usePersonaSign.ts
Expand Up @@ -7,7 +7,7 @@ export function usePersonaSign(message?: string, currentIdentifier?: ECKeyIdenti
if (!message || !currentIdentifier) return
try {
return await Services.Identity.signWithPersona({
method: 'eth',
method: 'message',
message,
identifier: currentIdentifier,
})
Expand Down
Expand Up @@ -27,6 +27,7 @@ export function useGasLimit(fallback = 50000) {
account,
})
if (!connection || !token?.address) return fallback

const web3 = connection.getWeb3({
chainId,
account,
Expand Down
Expand Up @@ -3,12 +3,38 @@ import { Web3ContextProvider } from '@masknet/web3-hooks-base'
import { NetworkPluginID } from '@masknet/shared-base'
import { ChainId } from '@masknet/web3-shared-evm'
import type { Web3Helper } from '@masknet/web3-helpers'
import { useValueRef } from '@masknet/shared-base-ui'
import { TrendingPopper } from './TrendingPopper.js'
import { TrendingView } from './TrendingView.js'
import { decentralizedSearchSettings } from '../../../../../shared/legacy-settings/settings.js'
import { useValueRef } from '@masknet/shared-base-ui'
import { TrendingViewProvider } from './context.js'

interface TrendingViewWrapperProps {
resultList: Web3Helper.TokenResultAll[]
address?: string
isNFTProjectPopper?: boolean
reposition?: () => void
}

function TrendingViewWrapper({ resultList, reposition, address, isNFTProjectPopper }: TrendingViewWrapperProps) {
const [result, setResult] = useState(resultList[0])
return (
<TrendingViewProvider
isNFTProjectPopper={Boolean(isNFTProjectPopper)}
isProfilePage={false}
isTokenTagPopper={!isNFTProjectPopper}
isPreciseSearch={false}>
<TrendingView
setResult={setResult}
result={result}
resultList={resultList}
onUpdate={reposition}
address={address}
/>
</TrendingViewProvider>
)
}

export interface TagInspectorProps {}

export function TagInspector(props: TagInspectorProps) {
Expand All @@ -30,23 +56,3 @@ export function TagInspector(props: TagInspectorProps) {
</Web3ContextProvider>
)
}

interface TrendingViewWrapperProps {
resultList: Web3Helper.TokenResultAll[]
address?: string
isNFTProjectPopper?: boolean
}

function TrendingViewWrapper({ resultList, address, isNFTProjectPopper }: TrendingViewWrapperProps) {
const [result, setResult] = useState<Web3Helper.TokenResultAll>()
const current = result ?? resultList[0]
return (
<TrendingViewProvider
isNFTProjectPopper={Boolean(isNFTProjectPopper)}
isProfilePage={false}
isTokenTagPopper={!isNFTProjectPopper}
isPreciseSearch={false}>
<TrendingView setResult={setResult} result={current} resultList={resultList} address={address} />
</TrendingViewProvider>
)
}
30 changes: 0 additions & 30 deletions packages/mask/src/plugins/Wallet/services/account.ts
@@ -1,35 +1,5 @@
import { first } from 'lodash-es'
import { defer, DeferTuple } from '@masknet/kit'
import type { ECKeyIdentifier, EnhanceableSite, ExtensionSite } from '@masknet/shared-base'
import { ChainId, isValidAddress } from '@masknet/web3-shared-evm'
import {
currentMaskWalletAccountSettings,
currentMaskWalletChainIdSettings,
} from '../../../../shared/legacy-settings/wallet-settings.js'
import { WalletRPC } from '../messages.js'

export async function setDefaultMaskAccount() {
if (currentMaskWalletAccountSettings.value) return
const wallets = await WalletRPC.getWallets()
const address = first(wallets)?.address
if (!address) return
await updateMaskAccount({
account: address,
})
}

export async function updateMaskAccount(options: { account?: string; chainId?: ChainId }) {
const { account, chainId } = options
if (chainId) currentMaskWalletChainIdSettings.value = chainId
if (isValidAddress(account)) {
currentMaskWalletAccountSettings.value = account
await resolveMaskAccount([
{
address: account,
},
])
}
}

const recordSites = new Map<EnhanceableSite | ExtensionSite, boolean>()

Expand Down