2021-03-18 19:23:46 +01:00
|
|
|
import { ethErrors, serializeError } from 'eth-rpc-errors';
|
2022-11-15 18:52:08 +01:00
|
|
|
import { isManifestV3 } from '../../../shared/modules/mv3.utils';
|
2021-03-18 19:23:46 +01:00
|
|
|
|
2022-11-15 18:52:08 +01:00
|
|
|
const createMetaRPCHandler = (api, outStream, store, localStoreApiWrapper) => {
|
2021-12-08 22:36:53 +01:00
|
|
|
return async (data) => {
|
2021-05-13 00:12:46 +02:00
|
|
|
if (outStream._writableState.ended) {
|
|
|
|
return;
|
|
|
|
}
|
2021-03-18 19:23:46 +01:00
|
|
|
if (!api[data.method]) {
|
|
|
|
outStream.write({
|
|
|
|
jsonrpc: '2.0',
|
|
|
|
error: ethErrors.rpc.methodNotFound({
|
|
|
|
message: `${data.method} not found`,
|
|
|
|
}),
|
|
|
|
id: data.id,
|
|
|
|
});
|
|
|
|
return;
|
|
|
|
}
|
2021-12-08 22:36:53 +01:00
|
|
|
|
|
|
|
let result;
|
|
|
|
let error;
|
|
|
|
try {
|
|
|
|
result = await api[data.method](...data.params);
|
|
|
|
} catch (err) {
|
|
|
|
error = err;
|
2022-11-15 18:52:08 +01:00
|
|
|
} finally {
|
|
|
|
if (isManifestV3 && store && data.method !== 'getState') {
|
|
|
|
localStoreApiWrapper.set(store.getState());
|
|
|
|
}
|
2021-12-08 22:36:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (outStream._writableState.ended) {
|
|
|
|
if (error) {
|
|
|
|
console.error(error);
|
2021-03-18 19:23:46 +01:00
|
|
|
}
|
2021-12-08 22:36:53 +01:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (error) {
|
|
|
|
outStream.write({
|
|
|
|
jsonrpc: '2.0',
|
|
|
|
error: serializeError(error, { shouldIncludeStack: true }),
|
|
|
|
id: data.id,
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
outStream.write({
|
|
|
|
jsonrpc: '2.0',
|
|
|
|
result,
|
|
|
|
id: data.id,
|
|
|
|
});
|
|
|
|
}
|
2021-03-18 19:23:46 +01:00
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export default createMetaRPCHandler;
|