1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-23 01:39:44 +01:00
metamask-extension/ui/hooks/flask/useTransactionInsightSnap.js
Frederik Bolding 13e4d3054b
[FLASK] Fix race condition with transaction insights (#16956)
* Fix race condition with transaction insights

* Rename variable
2022-12-14 19:50:23 +01:00

68 lines
1.8 KiB
JavaScript

import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { getTransactionOriginCaveat } from '@metamask/snaps-controllers';
import { handleSnapRequest } from '../../store/actions';
import { getPermissionSubjects } from '../../selectors';
const INSIGHT_PERMISSION = 'endowment:transaction-insight';
export function useTransactionInsightSnap({
transaction,
chainId,
origin,
snapId,
}) {
const subjects = useSelector(getPermissionSubjects);
const permission = subjects[snapId]?.permissions[INSIGHT_PERMISSION];
if (!permission) {
throw new Error(
'This snap does not have the transaction insight endowment.',
);
}
const hasTransactionOriginCaveat = getTransactionOriginCaveat(permission);
const transactionOrigin = hasTransactionOriginCaveat ? origin : null;
const [loading, setLoading] = useState(true);
const [data, setData] = useState(undefined);
const [error, setError] = useState(undefined);
useEffect(() => {
let cancelled = false;
async function fetchInsight() {
try {
setError(undefined);
setLoading(true);
const newData = await handleSnapRequest({
snapId,
origin: '',
handler: 'onTransaction',
request: {
jsonrpc: '2.0',
method: ' ',
params: { transaction, chainId, transactionOrigin },
},
});
if (!cancelled) {
setData(newData);
}
} catch (err) {
if (!cancelled) {
setError(err);
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
}
if (transaction) {
fetchInsight();
}
return () => (cancelled = true);
}, [snapId, transaction, chainId, transactionOrigin]);
return { data, error, loading };
}