import { useCallback } from 'react' ; import { useRedPacketContract } from './useRedPacketContract' ; import { TransactionEventType , TransactionStateType , useTransactionState } from '@masknet/web3-shared-evm' ; import type { NonPayableTx } from '@masknet/web3-contracts/types/types' ; import type { TransactionReceipt } from 'web3-core' ; export function useRefundCallback ( version , from , id ? ) { const [ refundState , setRefundState ] = useTransactionState ( ) ; const redPacketContract = useRedPacketContract ( version ) ; const refundCallback = useCallback ( async ( ) => { if ( ! redPacketContract || ! id ) { setRefundState ( { type : TransactionStateType . UNKNOWN , } ) ; return ; } setRefundState ( { type : TransactionStateType . WAIT_FOR_CONFIRMING , } ) ; const config = { from , gas : await redPacketContract . methods . refund ( id ) . estimateGas ( { from , } ) . catch ( ( error ) => { setRefundState ( { type : TransactionStateType . FAILED , error , } ) ; throw error ; } ) , } ; return new Promise < void > ( ( resolve , reject ) => { redPacketContract . methods . refund ( id ) . send ( config as NonPayableTx ) . on ( TransactionEventType . RECEIPT , ( receipt ) => { setRefundState ( { type : TransactionStateType . CONFIRMED , no : 0 , receipt , } ) ; resolve ( ) ; } ) . on ( TransactionEventType . CONFIRMATION , ( no , receipt ) => { setRefundState ( { type : TransactionStateType . CONFIRMED , no , receipt , } ) ; resolve ( ) ; } ) . on ( TransactionEventType . ERROR , ( error ) => { setRefundState ( { type : TransactionStateType . FAILED , error , } ) ; reject ( error ) ; } ) ; } ) ; } , [ id , redPacketContract , from ] ) ; const resetCallback = useCallback ( ( ) => { setRefundState ( { type : TransactionStateType . UNKNOWN , } ) ; } , [ ] ) ; return [ refundState , refundCallback , resetCallback ] as const ; }