如何使用typescript调用useContractReads?

bnlyeluc  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(115)

我尝试使用wagmi和typescript,但我对typescript很陌生。传递一个地址作为arg抛出一个错误,什么是解决这个问题的方法?
我读过https://wagmi.sh/docs/typescript,我也尝试过创建一个自定义接口(并定义arg?:...)的configCryptoDevsToken,但是当我提供合同对象时,调用useContractReads失败了,我甚至不确定这是正确的方法。
有一个mwe:here

import { abi } from "../constants/CryptoDevsToken";
import { useContractReads } from "wagmi";

export function useCryptoDevsToken(address: string | undefined) {
  const configCryptoDevsToken = {
    address: "CRYPTODEVSTOKEN_GOERLI_ADDRESS",
    abi: abi,
  };
  let contracts = [
    {
      ...configCryptoDevsToken,
      functionName: "maxSupply",
    },
  ];
  if (address) {
    contracts.push({
      ...configCryptoDevsToken,
      functionName: "balanceOf",
      args: [address], // throwing an error, see below
    });
  }
  const { data } = useContractReads({
    contracts: contracts,
  });
  return { data };
}

抛出的错误

Argument of type '{ functionName: string; args: string[]; address: string; abi: ({ inputs: { internalType: string; name: string; type: string; }[]; stateMutability: string; type: string; anonymous?: undefined; name?: undefined; outputs?: undefined; } | { ...; } | { ...; } | { ...; })[]; }' is not assignable to parameter of type '{ functionName: string; address: string; abi: ({ inputs: { internalType: string; name: string; type: string; }[]; stateMutability: string; type: string; anonymous?: undefined; name?: undefined; outputs?: undefined; } | { ...; } | { ...; } | { ...; })[]; }'.
Object literal may only specify known properties, and 'args' does not exist in type '{ functionName: string; address: string; abi: ({ inputs: { internalType: string; name: string; type: string; }[]; stateMutability: string; type: string; anonymous?: undefined; name?: undefined; outputs?: undefined; } | { ...; } | { ...; } | { ...; })[]; }'.
pb3s4cty

pb3s4cty1#

您的错误看起来像是ABI中的类型错误。
为了让wagmi在abis上使用类型推断,你需要使用constAssert。这里将进一步解释。https://wagmi.sh/core/typescript
我会这么做

import { useContractReads } from "wagmi";
import ABI from "../abis/abi.json";
const { abi: MY_ABI } = ABI;

export function useCryptoDevsToken(address: string | undefined) {
  const configCryptoDevsToken = {
    address: "CRYPTODEVSTOKEN_GOERLI_ADDRESS",
    abi: MULTICALL_ABI,
  };
  let contracts = [
    {
      ...configCryptoDevsToken,
      functionName: "maxSupply",
    },
  ];
  if (address) {
    contracts.push({
      ...configCryptoDevsToken,
      functionName: "balanceOf",
      args: [address], // throwing an error, see below
    });
  }
  const { data } = useContractReads({
    contracts: contracts,
  });
  return { data };
}

相关问题