import { FaucetService } from '@services/ApiService/Faucet' ; import { StoreAccount } from '@types' ; import { TUseStateReducerFactory } from '@utils' ; import { FaucetState , ITxFaucetResult } from './types' ; const FaucetFactory = ( { state , setState } ) => { const reset = ( ) => { setState ( ( ) => ( { step : 0 , loading : false } ) ) ; } ; const setSolution = ( solution ) => { setState ( ( prevState ) => ( { ... prevState , solution } ) ) ; } ; const requestFunds = ( recipientAddress ) => { const network = recipientAddress . network . name . toLowerCase ( ) ; const address = recipientAddress . address ; FaucetService . requestChallenge ( network , address ) . then ( ( result ) => { if ( ! result . success ) { throw new Error ( result . message ) ; } else { setState ( ( prevState ) => ( { ... prevState , challenge : result . result , step : 1 } ) ) ; } } ) . catch ( ( e ) => { setState ( ( prevState ) => ( { ... prevState , error : e . message } ) ) ; } ) ; } ; const finalizeRequestFunds = ( solutionInput ) => { if ( state . challenge ) { const challengeID = state . challenge . id ; setState ( ( prevState ) => ( { ... prevState , loading : true } ) ) ; FaucetService . solveChallenge ( challengeID , solutionInput ) . then ( ( result ) => { if ( ! result . success ) { throw new Error ( result . message ) ; } else { setState ( ( prevState ) => ( { ... prevState , loading : false , txResult : result . result as ITxFaucetResult , step : 2 } ) ) ; } } ) . catch ( ( e ) => { if ( e . message === 'INVALID_SOLUTION' ) { FaucetService . regenerateChallenge ( challengeID ) . then ( ( result ) => { if ( ! result . success ) { throw new Error ( result . message ) ; } else { setState ( ( prevState ) => ( { ... prevState , solution : '' , challenge : result . result , error : e . message , loading : false } ) ) ; } } ) . catch ( ( err ) => { setState ( ( prevState ) => ( { ... prevState , error : err . message } ) ) ; } ) ; } else { setState ( ( prevState ) => ( { ... prevState , loading : false , error : e . message } ) ) ; } } ) ; } } ; return { reset , setSolution , requestFunds , finalizeRequestFunds , faucetState : state } ; } ; export default FaucetFactory ;