Skip to content

Commit eb86be7

Browse files
committed
feat: Add isWalletInstalled and enableWallet extension helpers
1 parent c01f1e3 commit eb86be7

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

src/wallets.ts

+46-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import {
2+
InjectedExtension,
3+
InjectedWindow,
4+
} from '@polkadot/extension-inject/types'
5+
16
/**
27
* Substrate Wallet Type(s)
38
*/
@@ -41,7 +46,7 @@ export const polkadotjs: SubstrateWallet = {
4146
}
4247

4348
export const subwallet: SubstrateWallet = {
44-
id: 'subwallet',
49+
id: 'subwallet-js',
4550
name: 'SubWallet',
4651
platforms: [SubstrateWalletPlatform.Browser],
4752
urls: {
@@ -95,9 +100,9 @@ export const nova: SubstrateWallet = {
95100
* Exporting all wallets separately
96101
*/
97102
export const allSubstrateWallets: SubstrateWallet[] = [
98-
polkadotjs,
99103
subwallet,
100104
talisman,
105+
polkadotjs,
101106
nova,
102107
]
103108

@@ -109,3 +114,42 @@ export const getSubstrateWallet = (id: string): SubstrateWallet | undefined => {
109114
(wallet) => wallet.id.toLowerCase() === id.toLowerCase(),
110115
)
111116
}
117+
118+
/*
119+
* Returns `true` if wallet is installed, `false` if not, and
120+
* `undefined` if the environment is not a client browser.
121+
*/
122+
export const isWalletInstalled = (wallet: SubstrateWallet) => {
123+
try {
124+
if (typeof window === 'undefined') return undefined
125+
const injectedWindow = window as Window & InjectedWindow
126+
const injectedExtension = injectedWindow?.injectedWeb3?.[wallet.id]
127+
return !!injectedExtension
128+
} catch (e) {
129+
return undefined
130+
}
131+
}
132+
133+
/**
134+
* Enables the given wallet (if existent) and returns the injected extension.
135+
*/
136+
export const enableWallet = async (
137+
wallet: SubstrateWallet,
138+
appName: string,
139+
) => {
140+
if (!isWalletInstalled(wallet)) return undefined
141+
142+
try {
143+
if (typeof window === 'undefined') return undefined
144+
const injectedWindow = window as Window & InjectedWindow
145+
const injectedWindowProvider = injectedWindow?.injectedWeb3?.[wallet.id]
146+
const injectedExtension: InjectedExtension = {
147+
...(await injectedWindowProvider?.enable(appName)),
148+
name: wallet.id,
149+
version: injectedWindowProvider.version,
150+
}
151+
return injectedExtension
152+
} catch (e) {
153+
return undefined
154+
}
155+
}

0 commit comments

Comments
 (0)