useDApp
useDApp copied to clipboard
Can not override the call signature of `send` function returned by useContractFunction
Intention
- To override the call signature of the
sendfunction returned by theuseContractFunctionhook 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.
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
>;
}