import { useCallback } from 'react' ; import Web3Utils from 'web3-utils' ; import { useRedPacketContract } from './useRedPacketContract' ; import type { NonPayableTx } from '@masknet/web3-contracts/types/types' ; import { useTransactionState , TransactionStateType , TransactionEventType } from '@masknet/web3-shared-evm' ; import type { TransactionReceipt } from 'web3-core' ; import type { HappyRedPacketV1 } from '@masknet/web3-contracts/types/HappyRedPacketV1' ; import type { HappyRedPacketV4 } from '@masknet/web3-contracts/types/HappyRedPacketV4' ; export function useClaimCallback ( version , from , id ? , password ? ) { const [ claimState , setClaimState ] = useTransactionState ( ) ; const redPacketContract = useRedPacketContract ( version ) ; const claimCallback = useCallback ( async ( ) => { if ( ! redPacketContract || ! id || ! password ) { setClaimState ( { type : TransactionStateType . UNKNOWN , } ) ; return ; } setClaimState ( { type : TransactionStateType . WAIT_FOR_CONFIRMING , } ) ; const claim = version === 4 ? ( ) => ( redPacketContract as HappyRedPacketV4 ) . methods . claim ( id , password , from ) : ( ) => ( redPacketContract as HappyRedPacketV1 ) . methods . claim ( id , password as string , from , Web3Utils . sha3 ( from ) ! ) ; const config = { from , gas : await claim ( ) . estimateGas ( { from , } ) . catch ( ( error ) => { setClaimState ( { type : TransactionStateType . FAILED , error , } ) ; throw error ; } ) , } ; return new Promise < void > ( ( resolve , reject ) => { claim ( ) . send ( config as NonPayableTx ) . on ( TransactionEventType . TRANSACTION_HASH , ( hash ) => { setClaimState ( { type : TransactionStateType . HASH , hash , } ) ; } ) . on ( TransactionEventType . CONFIRMATION , ( no , receipt ) => { setClaimState ( { type : TransactionStateType . CONFIRMED , no , receipt , } ) ; resolve ( ) ; } ) . on ( TransactionEventType . ERROR , ( error ) => { setClaimState ( { type : TransactionStateType . FAILED , error , } ) ; reject ( error ) ; } ) ; } ) ; } , [ id , password , from , redPacketContract ] ) ; const resetCallback = useCallback ( ( ) => { setClaimState ( { type : TransactionStateType . UNKNOWN , } ) ; } , [ ] ) ; return [ claimState , claimCallback , resetCallback ] as const ; }