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