useDApp icon indicating copy to clipboard operation
useDApp copied to clipboard

Can not override the call signature of `send` function returned by useContractFunction

Open Stanley-Okwii opened this issue 5 years ago • 1 comments

Intention

  • To override the call signature of the send function returned by the useContractFunction hook such that we can maintain the types for the contracts we use.

Description

We got this code snippet that wraps the useContractFunction hook

File: useContractFunction.ts

import {
  TransactionStatus,
  useContractFunction as DappsUseContractFunction,
} from '@usedapp/core';
import { Contract } from 'ethers';

interface UseContractReturnType<
  ContractType extends Contract,
  Key extends keyof ContractType['functions'],
  Args extends Parameters<ContractType['functions'][Key]>,
> {
  send: (...args: Args) => Promise<void>;
  state: TransactionStatus;
}

function useContractFunction<
  ContractType extends Contract,
  Key extends keyof ContractType['functions'],
  Args extends Parameters<ContractType['functions'][Key]>,
>(
  contract: Contract,
  functionName: Key,
): UseContractReturnType<ContractType, Key, Args> {
  const { send, state } = DappsUseContractFunction(
    contract,
    functionName as string,
  );
  const useSend = (...args: Args) => {
    return send(...args);
  };
  return { send: useSend, state } as UseContractReturnType<
    ContractType,
    Key,
    Args
  >;
}

export { useContractFunction };

The above-customized hook is imported and used here File: index.tsx

import { useContractFunction } from '../../hooks/useContractFunction';

const { send } = useContractFunction(contracts.staking, 'stake');
send(param1,param2) // Parameters param1 and param2 do not have the types expected by the stake method of the contract

Parameters param1 and param2 from the snippet above, do not have the types expected by the stake method of the contract.

Stanley-Okwii avatar Sep 09 '21 09:09 Stanley-Okwii

Thanks to @anthonymartin ,

This is resolved. Resolution is the use ContractType instead of Contract like below

function useContractFunction<
  ContractType extends Contract,
  Key extends keyof ContractType['functions'],
  Args extends Parameters<ContractType['functions'][Key]>,
>(
  contract: ContractType,
  functionName: Key,
): UseContractReturnType<ContractType, Key, Args> {
  const { send, state } = DappsUseContractFunction(
    contract,
    functionName as string,
  );
  const useSend = (...args: Args) => {
    return send(...args);
  };
  return { send: useSend, state } as UseContractReturnType<
    ContractType,
    Key,
    Args
  >;
}

Stanley-Okwii avatar Sep 09 '21 10:09 Stanley-Okwii