Skip to content

Commit

Permalink
chore: tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
tmm committed Oct 17, 2024
1 parent 5b0b271 commit 4c03f34
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions packages/connectors/src/metaMask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,18 @@ export function metaMask(parameters: MetaMaskParameters = {}) {
type: metaMask.type,
async setup() {
const provider = await this.getProvider()
if (provider && !connect) {
connect = this.onConnect.bind(this)
provider.on('connect', connect as Listener)
if (provider?.on) {
if (!connect) {
connect = this.onConnect.bind(this)
provider.on('connect', connect as Listener)
}

// We shouldn't need to listen for `'accountsChanged'` here since the `'connect'` event should suffice (and wallet shouldn't be connected yet).
// Some wallets, like MetaMask, do not implement the `'connect'` event and overload `'accountsChanged'` instead.
if (!accountsChanged) {
accountsChanged = this.onAccountsChanged.bind(this)
provider.on('accountsChanged', accountsChanged as Listener)
}
}
},
async connect({ chainId, isReconnecting } = {}) {
Expand Down Expand Up @@ -193,10 +202,6 @@ export function metaMask(parameters: MetaMaskParameters = {}) {
const provider = await this.getProvider()

// Manage EIP-1193 event listeners
if (accountsChanged) {
provider.removeListener('accountsChanged', accountsChanged)
accountsChanged = undefined
}
if (chainChanged) {
provider.removeListener('chainChanged', chainChanged)
chainChanged = undefined
Expand Down Expand Up @@ -386,13 +391,15 @@ export function metaMask(parameters: MetaMaskParameters = {}) {
}
},
async onAccountsChanged(accounts) {
// Empty account list is the signal to disconnect from extension
// Disconnect if there are no accounts
if (accounts.length === 0) {
// ... and using browser extension
if (sdk.isExtensionActive()) this.onDisconnect()
return
// mobile app sometimes emits invalid `accountsChanged` event with empty accounts array
else return
}
// Connect if emitter is listening for connect event (e.g. is disconnected and connects through wallet interface)
if (config.emitter.listenerCount('connect')) {
else if (config.emitter.listenerCount('connect')) {
const chainId = (await this.getChainId()).toString()
this.onConnect({ chainId })
}
Expand Down Expand Up @@ -443,10 +450,6 @@ export function metaMask(parameters: MetaMaskParameters = {}) {
config.emitter.emit('disconnect')

// Manage EIP-1193 event listeners
if (!accountsChanged) {
accountsChanged = this.onAccountsChanged.bind(this)
provider.on('accountsChanged', accountsChanged as Listener)
}
if (chainChanged) {
provider.removeListener('chainChanged', chainChanged)
chainChanged = undefined
Expand Down

0 comments on commit 4c03f34

Please sign in to comment.