Skip to content

Commit

Permalink
fix: bug.
Browse files Browse the repository at this point in the history
  • Loading branch information
web3max committed Jan 11, 2024
1 parent 938b79d commit 5ca7b14
Show file tree
Hide file tree
Showing 23 changed files with 226 additions and 230 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "wallet-bridge",
"private": false,
"version": "0.1.60",
"version": "0.1.61-beta.3",
"main": "./dist/wallet-bridge.umd.js",
"module": "./dist/wallet-bridge.es.js",
"types": "./dist/index.d.ts",
Expand Down
26 changes: 26 additions & 0 deletions src/lib/components/Icons/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -559,3 +559,29 @@ export function QRCodeIcon(props: React.SVGProps<SVGSVGElement>) {
</svg>
)
}

export function TorusIcon(props: React.SVGProps<SVGSVGElement>) {
const { className, ...rest } = props
return (
<svg
className={clsx('icon', className)}
width="203"
height="219"
viewBox="0 0 203 219"
fill="none"
xmlns="http://www.w3.org/2000/svg"
{...rest}
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M20.4865 0C9.1721 0 0 9.17208 0 20.4864V44.3516C0 55.6659 9.17209 64.838 20.4864 64.838H56.7325V198.342C56.7325 209.656 65.9046 218.828 77.219 218.828H101.084C112.398 218.828 121.571 209.656 121.571 198.342V44.525C121.571 44.4673 121.571 44.4095 121.571 44.3516V20.4865C121.571 9.1721 112.399 0 101.085 0H77.219H20.4865Z"
fill="currentColor"
/>
<path
d="M170.209 64.838C188.114 64.838 202.628 50.3235 202.628 32.419C202.628 14.5145 188.114 0 170.209 0C152.305 0 137.79 14.5145 137.79 32.419C137.79 50.3235 152.305 64.838 170.209 64.838Z"
fill="currentColor"
/>
</svg>
)
}
30 changes: 28 additions & 2 deletions src/lib/ui/LoggedIn/LoggedIn.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
import { CopyIcon, DeviceIcon, DisconnectIcon, Header, QRCodeIcon, SwapChildProps, SwitchIcon } from '../../components'
import {
CopyIcon,
DeviceIcon,
DisconnectIcon,
Header,
QRCodeIcon,
SwapChildProps,
SwitchIcon,
TorusIcon,
} from '../../components'
import { CoinType, WalletProtocol } from '../../constant'
import { backupDeviceData, getAuthorizeInfo, getDotbitAlias, getMastersAddress, useWalletState } from '../../store'
import { ReactNode, useContext, useEffect, useState } from 'react'
import { ReactNode, useContext, useEffect, useMemo, useState } from 'react'
import { collapseString, copyText } from '../../utils'
import { WalletSDKContext } from '../ConnectWallet'
import { useSimpleRouter } from '../../components/SimpleRouter'
Expand Down Expand Up @@ -87,6 +96,14 @@ export const LoggedIn = ({ transitionRef, transitionStyle }: SwapChildProps) =>
})
}

const openTorus = () => {
walletSDK?.context?.torusWallet?.showWallet?.('home')
}

const showOpenTorusButton = useMemo(() => {
return !!walletSDK?.context?.torusWallet?.isLoggedIn
}, [walletSDK?.context?.torusWallet?.isLoggedIn])

useEffect(() => {
void getMastersAddress()
void getAuthorizeInfo().then(() => {
Expand Down Expand Up @@ -191,6 +208,15 @@ export const LoggedIn = ({ transitionRef, transitionStyle }: SwapChildProps) =>
>
{t`QR Code`}
</LoggedInButton>
{showOpenTorusButton && (
<LoggedInButton
className="flex-loggedin-button"
icon={<TorusIcon className="h-4 w-4 text-[#5F6570]"></TorusIcon>}
onClick={openTorus}
>
{t`Open Torus`}
</LoggedInButton>
)}
<LoggedInButton
className="flex-loggedin-button"
icon={<DisconnectIcon className="h-5 w-5 text-[#5F6570]"></DisconnectIcon>}
Expand Down
2 changes: 1 addition & 1 deletion src/lib/ui/Login/ChainList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ export const ChainList = ({ transitionStyle, transitionRef }: SwapChildProps) =>
await walletSDK.connect()
onClose()
} catch (error: any) {
console.error(error)
const handleErrorRes = handleError(error)
if (handleErrorRes.isHandle) {
if (handleErrorRes.title && handleErrorRes.message) {
Expand All @@ -139,6 +138,7 @@ export const ChainList = ({ transitionStyle, transitionRef }: SwapChildProps) =>
})
}
} else {
console.error(error)
createTips({
title: t`Tips`,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
Expand Down
2 changes: 1 addition & 1 deletion src/lib/ui/Login/Connect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,6 @@ export const Connect = ({ transitionStyle, transitionRef }: SwapChildProps) => {
onClose()
}
} catch (error: any) {
console.error(error)
const handleErrorRes = handleError(error)
if (handleErrorRes.isHandle) {
if (handleErrorRes.title && handleErrorRes.message) {
Expand All @@ -132,6 +131,7 @@ export const Connect = ({ transitionStyle, transitionRef }: SwapChildProps) => {
})
}
} else {
console.error(error)
createTips({
title: t`Tips`,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
Expand Down
2 changes: 1 addition & 1 deletion src/lib/ui/Login/WalletList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ export const WalletList = ({ transitionRef, transitionStyle }: SwapChildProps) =
onClose?.()
setLoginCacheState({ walletConnectDisplayUri: '', walletName: '' })
} catch (error: any) {
console.error(error)
const handleErrorRes = handleError(error)
if (handleErrorRes.isHandle) {
if (handleErrorRes.title && handleErrorRes.message) {
Expand All @@ -129,6 +128,7 @@ export const WalletList = ({ transitionRef, transitionStyle }: SwapChildProps) =
})
}
} else {
console.error(error)
createTips({
title: t`Tips`,
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
Expand Down
13 changes: 12 additions & 1 deletion src/lib/ui/Wallet/wallet.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const wagmiConfig = createConfig({
})

const wallet = new Wallet({
isTestNet: false,
isTestNet: true,
wagmiConfig,
})

Expand Down Expand Up @@ -125,6 +125,15 @@ const TemplateConnectWallet = () => {
console.log(res)
}

const onSignData712 = async () => {
const mmJson =
'{"types":{"EIP712Domain":[{"name":"chainId","type":"uint256"},{"name":"name","type":"string"},{"name":"verifyingContract","type":"address"},{"name":"version","type":"string"}],"Action":[{"name":"action","type":"string"},{"name":"params","type":"string"}],"Cell":[{"name":"capacity","type":"string"},{"name":"lock","type":"string"},{"name":"type","type":"string"},{"name":"data","type":"string"},{"name":"extraData","type":"string"}],"Transaction":[{"name":"DAS_MESSAGE","type":"string"},{"name":"inputsCapacity","type":"string"},{"name":"outputsCapacity","type":"string"},{"name":"fee","type":"string"},{"name":"action","type":"Action"},{"name":"inputs","type":"Cell[]"},{"name":"outputs","type":"Cell[]"},{"name":"digest","type":"bytes32"}]},"primaryType":"Transaction","domain":{"chainId":1,"name":"da.systems","verifyingContract":"0x0000000000000000000000000000000020210722","version":"1"},"message":{"DAS_MESSAGE":"TRANSFER FROM 0x54366bcd1e73baf55449377bd23123274803236e(906.74221046 CKB) TO ckt1qyqvsej8jggu4hmr45g4h8d9pfkpd0fayfksz44t9q(764.13228446 CKB), 0x54366bcd1e73baf55449377bd23123274803236e(142.609826 CKB)","inputsCapacity":"906.74221046 CKB","outputsCapacity":"906.74211046 CKB","fee":"0.0001 CKB","digest":"0x29cd28dbeb470adb17548563ceb4988953fec7b499e716c16381e5ae4b04021f","action":{"action":"transfer","params":"0x00"},"inputs":[],"outputs":[]}}'
const signature = await wallet.walletSDK.signData(JSON.parse(mmJson), {
isEIP712: true,
})
console.log(signature)
}

const onSendTransaction = async () => {
const signature = await wallet.sendTransaction({
to: '0x7df93d9F500fD5A9537FEE086322a988D4fDCC38',
Expand Down Expand Up @@ -167,6 +176,8 @@ const TemplateConnectWallet = () => {
<br />
<Button onClick={onSignData}>Sign data</Button>
<br />
<Button onClick={onSignData712}>Sign data 712</Button>
<br />
<Button onClick={onSendTransaction}>Send transaction</Button>
<br />
<Button
Expand Down
4 changes: 1 addition & 3 deletions src/lib/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,6 @@ export async function checkWebAuthnSupport(): Promise<boolean> {
return false
}
} catch (error) {
console.error(error)
return false
}
} else {
Expand All @@ -298,13 +297,12 @@ export async function checkWebAuthnSupport(): Promise<boolean> {
*/
export async function checkICloudPasskeySupport() {
const uaParser = new UAParser(globalThis.navigator?.userAgent)
let platformVersion: number
let platformVersion: number = 0
try {
// @ts-expect-error
const highEntropyValues = await globalThis.navigator?.userAgentData?.getHighEntropyValues(['platformVersion'])
platformVersion = parseInt(highEntropyValues?.platformVersion?.split('.')[0] ?? '0', 10)
} catch (e) {
console.error(e)
platformVersion = 0
}

Expand Down
137 changes: 59 additions & 78 deletions src/lib/wallets/WalletConnectorHandler/MetaMaskConnector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,80 +4,68 @@ import { connect, Connector, disconnect, getNetwork, switchNetwork } from '@wagm
import { EventEnum } from '../WalletEventListenerHandler'
import { resetWalletState, setWalletState } from '../../store'
import { isMobile } from 'react-device-detect'
import { CoinTypeToChainMap } from '../../constant'
import { snapshot } from 'valtio'
import { loginCacheState, setLoginCacheState } from '../../store/loginCache'
import { MetaMaskSigner, SignDataType } from '../WalletSignerHandler'
import { t } from '@lingui/macro'

export class MetaMaskConnector extends WalletConnector {
async connect({ ignoreEvent }: { ignoreEvent: boolean } = { ignoreEvent: false }) {
try {
const { wagmiConfig, chainId, provider, walletName } = this.context
const { wagmiConfig, chainId, provider, walletName } = this.context

let connector
if (shouldUseWalletConnect()) {
connector = wagmiConfig.connectors.find((item: Connector) => {
return item.id === 'walletConnect' && item.options.showQrModal === false
})
} else {
connector = wagmiConfig.connectors.find((item: Connector) => {
return item.id === 'injected'
})
}
let connector
if (shouldUseWalletConnect()) {
connector = wagmiConfig.connectors.find((item: Connector) => {
return item.id === 'walletConnect' && item.options.showQrModal === false
})
} else {
connector = wagmiConfig.connectors.find((item: Connector) => {
return item.id === 'injected'
})
}

// eslint-disable-next-line lingui/no-unlocalized-strings
const walletStateLocalStorage = globalThis.localStorage.getItem('WalletState')
if (walletStateLocalStorage && wagmiConfig.status === 'connected') {
await disconnect()
// eslint-disable-next-line lingui/no-unlocalized-strings
const walletStateLocalStorage = globalThis.localStorage.getItem('WalletState')
if (walletStateLocalStorage && wagmiConfig.status === 'connected') {
await disconnect()
// eslint-disable-next-line lingui/no-unlocalized-strings
globalThis.localStorage.removeItem('WalletState')
}
globalThis.localStorage.removeItem('WalletState')
}

if (wagmiConfig && wagmiConfig.status !== 'connected' && connector) {
if (shouldUseWalletConnect()) {
provider.once('display_uri', async (uri: string) => {
if (isMobile) {
if (walletName) {
const deepLink = getWalletDeepLink(walletName, uri)
openDeepLink(deepLink)
}
} else {
// eslint-disable-next-line lingui/no-unlocalized-strings
console.log('WalletConnect display_uri', uri)
setLoginCacheState({ walletConnectDisplayUri: uri })
if (wagmiConfig && wagmiConfig.status !== 'connected' && connector) {
if (shouldUseWalletConnect()) {
provider.once('display_uri', async (uri: string) => {
if (isMobile) {
if (walletName) {
const deepLink = getWalletDeepLink(walletName, uri)
openDeepLink(deepLink)
}
})
}

const { chain, account } = await connect({
connector,
chainId,
} else {
// eslint-disable-next-line lingui/no-unlocalized-strings
console.log('WalletConnect display_uri', uri)
setLoginCacheState({ walletConnectDisplayUri: uri })
}
})
}

if (chainId && chainId !== chain.id && !shouldUseWalletConnect()) {
await this.switchNetwork(chainId)
}
const { chain, account } = await connect({
connector,
chainId,
})

const network = getNetwork()
if (chainId && chainId !== chain.id && !shouldUseWalletConnect()) {
await this.switchNetwork(chainId)
}

if (account && network.chain && network.chain.id === chainId) {
this.context.address = toChecksumAddress(account)
setWalletState({
protocol: this.context.protocol,
address: this.context.address,
coinType: this.context.coinType,
walletName: this.context.walletName,
})
const { signDataParams } = snapshot(loginCacheState)
if (signDataParams) {
const signature = await this.signData(signDataParams.data as SignDataType, signDataParams.isEIP712)
this.context.emitEvent(EventEnum.Signature, signature)
} else if (!ignoreEvent) {
this.context.emitEvent(EventEnum.Connect)
}
}
} else if (wagmiConfig.status === 'connected') {
const network = getNetwork()

if (account && network.chain && network.chain.id === chainId) {
this.context.address = toChecksumAddress(account)
setWalletState({
protocol: this.context.protocol,
address: this.context.address,
coinType: this.context.coinType,
walletName: this.context.walletName,
})
const { signDataParams } = snapshot(loginCacheState)
if (signDataParams) {
const signature = await this.signData(signDataParams.data as SignDataType, signDataParams.isEIP712)
Expand All @@ -86,15 +74,13 @@ export class MetaMaskConnector extends WalletConnector {
this.context.emitEvent(EventEnum.Connect)
}
}
} catch (err) {
console.error(err)
if (isMobile) {
throw new Error(t`Please open this page in your crypto wallet App and try again.`)
} else {
const name = this.context.coinType && CoinTypeToChainMap[this.context.coinType].name
throw new Error(
t`Please ensure that your browser has the ${String(name)} wallet plugin installed and try again.`,
)
} else if (wagmiConfig.status === 'connected') {
const { signDataParams } = snapshot(loginCacheState)
if (signDataParams) {
const signature = await this.signData(signDataParams.data as SignDataType, signDataParams.isEIP712)
this.context.emitEvent(EventEnum.Signature, signature)
} else if (!ignoreEvent) {
this.context.emitEvent(EventEnum.Connect)
}
}
}
Expand All @@ -115,15 +101,10 @@ export class MetaMaskConnector extends WalletConnector {
}

async signData(data: SignDataType, isEIP712?: boolean): Promise<string | undefined> {
try {
const signer = new MetaMaskSigner(this.context)
await sleep(1000)
return await signer.signData(data, {
isEIP712,
})
} catch (err) {
console.error(err)
return undefined
}
const signer = new MetaMaskSigner(this.context)
await sleep(1000)
return await signer.signData(data, {
isEIP712,
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,7 @@ export class TokenPocketUTXOConnector extends WalletConnector {
async switchNetwork(chainId: number): Promise<void> {}

async signData(data: SignDataType): Promise<string | undefined> {
try {
const signer = new TokenPocketUTXOSigner(this.context)
return await signer.signData(data)
} catch (err) {
console.error(err)
return undefined
}
const signer = new TokenPocketUTXOSigner(this.context)
return await signer.signData(data)
}
}
Loading

0 comments on commit 5ca7b14

Please sign in to comment.