Skip to content
This repository has been archived by the owner on Jun 3, 2024. It is now read-only.

Ft/add meta mask snap #83

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"react-icons": "^4.11.0",
"react-merge-refs": "^2.0.1",
"styled-components": "^6.0.0",
"wagmi": "^1.4.12",
"zustand": "^4.4.4"
},
"devDependencies": {
Expand Down
179 changes: 172 additions & 7 deletions src/components/wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,28 @@ import {
ModalHeader,
ModalOverlay,
Text,
VStack
VStack,
useToast
} from '@chakra-ui/react'
import { ApiPromise } from '@polkadot/api'
import { encodeAddress } from '@polkadot/keyring'
import { WsProvider } from '@polkadot/rpc-provider'
import { enableSubspaceSnap } from '@subspace/metamask-subspace-adapter'
import type { MetamaskSubspaceSnap } from '@subspace/metamask-subspace-adapter/build/snap'
import Image from 'next/image'
import { useRef } from 'react'
import { useCallback, useRef } from 'react'
import { useConnect as useConnectWagmi } from 'wagmi' // , useDisconnect
import { connectWalletButtonStyles } from '../constants'
import { useConnect } from '../hooks/useConnect'
import { useExtension } from '../states/extension'
import { useExtension, useLastConnection, useTransactions } from '../states/extension'
import { formatAddress } from '../utils'

interface ExtensionIconProps {
extension: string
}

export const defaultSnapId = 'local:http://localhost:8081'

const ExtensionIcon: React.FC<ExtensionIconProps> = ({ extension }) => {
switch (extension) {
case 'polkadot-js':
Expand All @@ -46,7 +54,21 @@ const ExtensionIcon: React.FC<ExtensionIconProps> = ({ extension }) => {
}

export const ConnectWallet = () => {
const { extension, subspaceAccount, chainDetails } = useExtension((state) => state)
const toast = useToast()
const {
api,
extension,
subspaceAccount,
chainDetails,
setSubspaceAccount,
setMMApi,
// setInjectedExtension,
setExtension
} = useExtension()
const { setSubspaceAccount: setLastSubspaceAccount } = useLastConnection()
// const { disconnectAsync } = useDisconnect()
const { connectors, connectAsync } = useConnectWagmi()
const { transactions, addTransactionToWatch } = useTransactions()
const {
handleSelectFirstWalletFromExtension,
handleSelectWallet,
Expand All @@ -58,6 +80,149 @@ export const ConnectWallet = () => {
const finalRef = useRef(null)
const { ss58Format } = chainDetails

const installSubspaceSnap = useCallback(async (): Promise<{
isSnapInstalled: boolean
snap?: MetamaskSubspaceSnap
}> => {
const snapId = process.env.REACT_APP_SNAP_ID ? process.env.REACT_APP_SNAP_ID : defaultSnapId
try {
// try {
// disconnectAsync && (await disconnectAsync())
// } catch (e) {
// console.error('e', e)
// }
try {
const connector = connectors.find((c) => c.id === 'metaMask')
connector && (await connectAsync({ connector }))
} catch (e) {
console.error('e', e)
}
const snap = await enableSubspaceSnap({ networkName: 'gemini-3g' }, snapId)
toast({
title: 'MetaMask Snap installed',
description: 'You can now use MetaMask Snap to connect to Subspace.',
status: 'success',
duration: 5000,
isClosable: true
})

const mmApi = snap.getMetamaskSnapApi()
const address = await mmApi.getAddress()
console.log('address', address)
const balance = await mmApi.getBalance()
console.log('balance', balance)

const allTx = await mmApi.getAllTransactions()
console.log('allTx', allTx)

if (!api) {
const wsProvider = new WsProvider(process.env.NEXT_PUBLIC_PROVIDER_URL)
const api = await ApiPromise.create({ provider: wsProvider })

const block = await api.rpc.chain.getBlock()
console.log('block', block)
} else {
const block = await api.rpc.chain.getBlock()
console.log('block', block.toHuman())
}

for (const tx of allTx) {
const isAlreadyWatched = transactions.find((t) => t.extrinsicHash === tx.hash)
if (!isAlreadyWatched)
addTransactionToWatch({
extrinsicHash: tx.hash,
method: '',
sender: tx.sender,
fromBlockNumber: 0
})
}

// const latestBlock = await mmApi.getLatestBlock()
// console.info('latestBlock:', latestBlock)
// const pubKey = await mmApi.getPublicKey()
// console.info('pubKey:', pubKey)

setSubspaceAccount(address)
setLastSubspaceAccount(address)

setMMApi(mmApi)
setExtension({
error: null,
loading: false,
data: {
accounts: extension.data
? [
...extension.data.accounts,
{
address: address,
meta: {
name: 'MetaMask',
source: 'metamask',
genesisHash: '0x0000000'
},
type: 'sr25519'
}
]
: [
{
address: address,
meta: {
name: 'MetaMask',
source: 'metamask',
genesisHash: '0x0000000'
},
type: 'sr25519'
}
],
defaultAccount: {
address: address,
meta: {
name: 'MetaMask',
source: 'metamask',
genesisHash: '0x0000000'
},
type: 'sr25519'
}
}
})
// setInjectedExtension({
// name: string;
// version: string;

// accounts: InjectedAccounts;
// metadata?: InjectedMetadata;
// provider?: InjectedProvider;
// signer: InjectedSigner;
// })

return { isSnapInstalled: true, snap }
} catch (err) {
console.error('SnapConnectorButton-Error:', err)
return { isSnapInstalled: false }
}
}, [
addTransactionToWatch,
api,
connectAsync,
connectors,
extension.data,
setExtension,
setLastSubspaceAccount,
setMMApi,
setSubspaceAccount,
toast,
transactions
])

const handleMetaMaskSnap = useCallback(async () => {
const installed = await installSubspaceSnap()
console.log('installed', installed)
if (installed.isSnapInstalled) {
// enableSnap(address)
onConnectClose()
}
}, [installSubspaceSnap, onConnectClose])

return (
<>
{!extension.data || !subspaceAccount ? (
Expand Down Expand Up @@ -131,12 +296,12 @@ export const ConnectWallet = () => {
</Button>
</GridItem>
{/* Uncomment when metamask snap is ready */}
{/* <GridItem>
<Button variant='outline' w='200px' borderColor='brand' onClick={() => handleSelectWallet('')}>
<GridItem>
<Button variant='outline' w='200px' borderColor='brand' onClick={() => handleMetaMaskSnap()}>
<ExtensionIcon extension='metamask' />
<Text ml='2'>MetaMask Snap</Text>
</Button>
</GridItem> */}
</GridItem>
</Grid>
</VStack>
</Center>
Expand Down
51 changes: 51 additions & 0 deletions src/context/snapProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import type { MetamaskSubspaceSnap } from '@subspace/metamask-subspace-adapter/build/snap'
import type { Dispatch, PropsWithChildren, Reducer } from 'react'
import React, { createContext, useReducer } from 'react'
import { hasMetaMask } from '../services/metamask'

interface ISubspaceSnap {
isInstalled: boolean
message: string
snap?: MetamaskSubspaceSnap
}

export interface MetamaskState {
subspaceSnap: ISubspaceSnap
hasMetaMask: boolean
}

const initialState: MetamaskState = {
hasMetaMask: hasMetaMask(),
subspaceSnap: {
isInstalled: false,
message: ''
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type MetamaskDispatch = { type: MetamaskActions; payload: any }

export const MetaMaskContext = createContext<[MetamaskState, Dispatch<MetamaskDispatch>]>([initialState, () => null])

export enum MetamaskActions {
SET_INSTALLED_STATUS
}

const reducer: Reducer<MetamaskState, MetamaskDispatch> = (state, action) => {
switch (action.type) {
case MetamaskActions.SET_INSTALLED_STATUS: {
return {
...state,
subspaceSnap: action.payload as ISubspaceSnap
}
}
default: {
return state
}
}
}

export const SnapContextProvider = (props: PropsWithChildren<Record<string, unknown>>): React.JSX.Element => {
const [state, dispatch] = useReducer(reducer, initialState)

return <MetaMaskContext.Provider value={[state, dispatch]}>{props.children}</MetaMaskContext.Provider>
}
Loading