Abi

web3.eth.Contract 出現問題,Typescript 使用 ABI

  • January 17, 2022

我在使用帶有 Typescript 的 web3.eth.Contract 時遇到了一些麻煩。

import * as ERC721ABI from "../ABIs/ERC721.json";
import Web3 from "web3";

...

const contract = new web3.eth.Contract(ERC721ABI, event.target.value);

...

我收到的錯誤是:

Argument of type '({ inputs: { internalType: string; name: string; type: string; }[]; stateMutability: string; type: string; anonymous?: undefined; name?: undefined; outputs?: undefined; } | { anonymous: boolean; inputs: { ...; }[]; name: string; type: string; stateMutability?: undefined; outputs?: undefined; } | { ...; })[]' is not assignable to parameter of type 'AbiItem | AbiItem[]'.
 Type '({ inputs: { internalType: string; name: string; type: string; }[]; stateMutability: string; type: string; anonymous?: undefined; name?: undefined; outputs?: undefined; } | { anonymous: boolean; inputs: { ...; }[]; name: string; type: string; stateMutability?: undefined; outputs?: undefined; } | { ...; })[]' is not assignable to type 'AbiItem[]'.
   Type '{ inputs: { internalType: string; name: string; type: string; }[]; stateMutability: string; type: string; anonymous?: undefined; name?: undefined; outputs?: undefined; } | { anonymous: boolean; inputs: { ...; }[]; name: string; type: string; stateMutability?: undefined; outputs?: undefined; } | { ...; }' is not assignable to type 'AbiItem'.
     Type '{ inputs: { internalType: string; name: string; type: string; }[]; stateMutability: string; type: string; anonymous?: undefined; name?: undefined; outputs?: undefined; }' is not assignable to type 'AbiItem'.
       Types of property 'stateMutability' are incompatible.
         Type 'string' is not assignable to type '"nonpayable" | "view" | "pure" | "payable" | undefined'.  TS2345

   90 | 
   91 |     try {
 > 92 |       const contract = new web3.eth.Contract(ERC721ABI, event.target.value);

知道我在這裡做錯了什麼嗎?

另外,是否可以將多個 ABI 導入 web3.eth.Contract,或者我必須為每個 ABI 創建單獨的實例?

最後,知道我需要使用哪個 ABI 來與錢包互動,還是需要單獨呼叫?我不太確定乙太坊上的錢包是否也是智能合約,或者只是一個公鑰。

謝謝

你也可以

import { AbiItem } from 'web3-utils'
import Abi from './abi.json'

new web3.eth.Contract(Abi as AbiItem[], contractAddress)

問題似乎來自 TypeScript 在使用 REACT 時如何導入 JSON 文件。

import而不是使用導入require

代替

import * as ERC721ABI from "../ABIs/ERC721.json";

const ERC721ABI  = require("../ABIs/ERC721.json");

有關更多資訊,您可以參考我發現問題的位置和解決方案:https ://github.com/ChainSafe/web3.js/issues/3310#issuecomment-701590114

引用自:https://ethereum.stackexchange.com/questions/94601