2022-12-21 09:29:32 +00:00
|
|
|
import { useVegaWallet } from './use-vega-wallet';
|
|
|
|
import { useEffect, useRef } from 'react';
|
2023-02-07 10:31:15 +00:00
|
|
|
import type { WalletError } from './connectors';
|
2022-12-21 09:29:32 +00:00
|
|
|
import { ClientErrors } from './connectors';
|
2023-02-07 10:31:15 +00:00
|
|
|
import { VegaTxStatus, orderErrorResolve } from './use-vega-transaction';
|
2022-12-21 09:29:32 +00:00
|
|
|
import { useVegaTransactionStore } from './use-vega-transaction-store';
|
|
|
|
|
|
|
|
export const useVegaTransactionManager = () => {
|
2023-02-07 10:31:15 +00:00
|
|
|
const { sendTx, pubKey, disconnect } = useVegaWallet();
|
2022-12-21 09:29:32 +00:00
|
|
|
const processed = useRef<Set<number>>(new Set());
|
|
|
|
const transaction = useVegaTransactionStore((state) =>
|
|
|
|
state.transactions.find(
|
|
|
|
(transaction) =>
|
|
|
|
transaction?.status === VegaTxStatus.Requested &&
|
|
|
|
!processed.current.has(transaction.id)
|
|
|
|
)
|
|
|
|
);
|
|
|
|
const update = useVegaTransactionStore((state) => state.update);
|
|
|
|
const del = useVegaTransactionStore((state) => state.delete);
|
|
|
|
useEffect(() => {
|
|
|
|
if (!(transaction && pubKey)) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
processed.current.add(transaction.id);
|
|
|
|
sendTx(pubKey, transaction.body)
|
|
|
|
.then((res) => {
|
|
|
|
if (res === null) {
|
|
|
|
// User rejected
|
|
|
|
del(transaction.id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (res.signature && res.transactionHash) {
|
|
|
|
update(transaction.id, {
|
|
|
|
status: VegaTxStatus.Pending,
|
|
|
|
txHash: res.transactionHash,
|
|
|
|
signature: res.signature,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.catch((err) => {
|
2023-02-07 10:31:15 +00:00
|
|
|
const error = orderErrorResolve(err);
|
|
|
|
if ((error as WalletError).code === ClientErrors.NO_SERVICE.code) {
|
|
|
|
disconnect();
|
|
|
|
}
|
2022-12-21 09:29:32 +00:00
|
|
|
update(transaction.id, {
|
2023-02-07 10:31:15 +00:00
|
|
|
error,
|
2022-12-21 09:29:32 +00:00
|
|
|
status: VegaTxStatus.Error,
|
|
|
|
});
|
|
|
|
});
|
2023-02-07 10:31:15 +00:00
|
|
|
}, [transaction, pubKey, del, sendTx, update, disconnect]);
|
2022-12-21 09:29:32 +00:00
|
|
|
};
|