1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-23 03:36:18 +02:00
metamask-extension/app/scripts/controllers/permissions/methodMiddleware.js
Whymarrh Whitby 92971d3c87
Migrate codebase to use ESM (#7730)
* Update eslint-plugin-import version

* Convert JS files to use ESM

* Update ESLint rules to check imports

* Fix test:unit:global command env

* Cleanup mock-dev script
2020-01-09 00:04:58 -03:30

90 lines
2.2 KiB
JavaScript

import createAsyncMiddleware from 'json-rpc-engine/src/createAsyncMiddleware'
import { ethErrors } from 'eth-json-rpc-errors'
/**
* Create middleware for handling certain methods and preprocessing permissions requests.
*/
export default function createMethodMiddleware ({
store, storeKey, getAccounts, requestAccountsPermission,
}) {
return createAsyncMiddleware(async (req, res, next) => {
if (typeof req.method !== 'string') {
res.error = ethErrors.rpc.invalidRequest({ data: req })
return
}
switch (req.method) {
// intercepting eth_accounts requests for backwards compatibility,
// i.e. return an empty array instead of an error
case 'eth_accounts':
res.result = await getAccounts()
return
case 'eth_requestAccounts':
// first, just try to get accounts
let accounts = await getAccounts()
if (accounts.length > 0) {
res.result = accounts
return
}
// if no accounts, request the accounts permission
try {
await requestAccountsPermission()
} catch (err) {
res.error = err
return
}
// get the accounts again
accounts = await getAccounts()
if (accounts.length > 0) {
res.result = accounts
} else {
// this should never happen
res.error = ethErrors.rpc.internal(
'Accounts unexpectedly unavailable. Please report this bug.'
)
}
return
// custom method for getting metadata from the requesting domain
case 'wallet_sendDomainMetadata':
const storeState = store.getState()[storeKey]
const extensionId = storeState[req.origin]
? storeState[req.origin].extensionId
: undefined
if (
req.domainMetadata &&
typeof req.domainMetadata.name === 'string'
) {
store.updateState({
[storeKey]: {
...storeState,
[req.origin]: {
extensionId,
...req.domainMetadata,
},
},
})
}
res.result = true
return
default:
break
}
next()
})
}