import { useEffect } from 'react' ; import { useSelector } from 'react-redux' ; import { useReducer } from 'reinspect' ; import { makePendingTxReceipt , makeTxConfigFromTx } from '@helpers' ; import { useAccounts , useAssets } from '@services' ; import { getStoreAccounts } from '@store' ; import { ITxObject , ITxStatus , ITxType , Network , StoreAccount } from '@types' ; import { identity , lensIndex , view } from '@vendor' ; import { init , initWith , prepareTx , reset , sendTx , stopYield } from './actions' ; import { initialState , TxMultiReducer } from './reducer' ; import { TxMultiState , TxParcel } from './types' ; export type TUseTxMulti = ( ) => { prepareTx : ReturnType < typeof prepareTx > ; sendTx : ReturnType < typeof sendTx > ; reset : ReturnType < typeof reset > ; currentTx : TxParcel ; state : TxMultiState ; init ( txs , account , network ) : Promise < void > ; initWith ( getTxs , account , network ) : Promise < void > ; stopYield ( ) : Promise < void > ; } ; export const useTxMulti = ( ) => { const [ state , dispatch ] = useReducer ( TxMultiReducer , initialState , identity , 'TxMulti' ) ; const getState = ( ) => state ; const accounts = useSelector ( getStoreAccounts ) ; const { addTxToAccount , getAccountByAddressAndNetworkName } = useAccounts ( ) ; const { assets } = useAssets ( ) ; const { network , account : stateAccount } = state ; const account = stateAccount && getAccountByAddressAndNetworkName ( stateAccount . address , stateAccount . networkId ) ; const currentTx = view ( lensIndex ( state . _currentTxIdx ) , state . transactions ) ; useEffect ( ( ) => { if ( account && network && currentTx && currentTx . txRaw && currentTx . txHash && currentTx . status === ITxStatus . BROADCASTED ) { const txType = currentTx . txType ?? ITxType . UNKNOWN ; const txConfig = makeTxConfigFromTx ( currentTx . txRaw , assets , network , accounts ) ; const pendingTxReceipt = makePendingTxReceipt ( currentTx . txHash ) ( txType , txConfig , currentTx . metadata ) ; addTxToAccount ( account , pendingTxReceipt ) ; } } , [ currentTx ] ) ; return { state , init : init ( dispatch ) , initWith : initWith ( dispatch ) , stopYield : stopYield ( dispatch ) , prepareTx : prepareTx ( dispatch , getState ) , sendTx : sendTx ( dispatch , getState ) , reset : reset ( dispatch ) , currentTx } ; } ;