import { Contract } from '@ethersproject/contracts' import { TransactionReceipt } from '@ethersproject/providers' import { map } from 'lodash' import { MutationOptions } from 'react-query' import { CustomError } from '../../utils' import Logger from '../../utils/logger/logger' import { useCustomMutation } from '../customQuery/useCustomMutation' import { ContractMethodName, UseQueryContractKey } from './types' import { getContractKey } from './utils' /** * @example * const key = [contract, 'methodName', [params]] * const key = { contract, methodName, params } * const { data, error, mutate } = useMutationContract(key) */ export function useMutationContract< TVariable = any, T extends Contract = Contract, N extends ContractMethodName = ContractMethodName, Error = any, Data = TransactionReceipt, >(key?: UseQueryContractKey | null, config: MutationOptions = {}) { const { callback } = key const { contract, methodName } = getContractKey(key) || {} // const serializedKeys = useMemo(() => serializesContractKey(key), [key]) const mutation = useCustomMutation( // [serializedKeys], async (variables?: any) => { const { contractParams } = variables let data = null if (!contract || !methodName) return null if (!contractParams) { data = contract[methodName]() } else { data = await contract[methodName](...map(contractParams, (i) => i)) } const receipt = await data.wait() const { status } = receipt if (!status) { throw new CustomError('Transaction failed', 999, receipt) } if (callback) { await callback({ variables, data: receipt }) } return receipt }, { // onMutate: async () => {}, // onSuccess: () => {}, onError: (err): Promise | void => { Logger.error(err) }, // onSettled: () => {}, ...config, }, ) return mutation }