获取合约实例时出错

问题描述 投票:0回答:1

我正在按照教程在 Polygon 网络上创建点对点支付 dApp。当我尝试获取 web3 提供商中的帐户并创建 PaymentToken 合约的实例时,我收到一条错误消息

Type 'bigint' cannot be used as an index type.ts(2538) const networkId: bigint

const loadWallet = async () => {
    if (window.ethereum) {
      window.web3 = new Web3(window.ethereum);
      await window.ethereum.enable();
      const web3 = window.web3;
      var allAccounts = await web3.eth.getAccounts();
      setAccount(allAccounts[0]);

      const web3_ = new Web3(window.web3.currentProvider);
      const networkId = await web3.eth.net.getId();

      // The error in the following line
      const paymentTokenData = PaymentToken.networks[networkId];
      if (paymentTokenData) {
        var paymentTokenInstance = new web3.eth.Contract(
          PaymentToken.abi,
          paymentTokenData.address
        );
        setPaymentToken(paymentTokenInstance);
        var bal = await paymentTokenInstance.methods
          .balanceOf(allAccounts[0])
          .call();
        setBalance(bal);
      } else {
        window.alert("TestNet not found");
      }
      setLoading(false);
    } else {
      window.alert("Non-Eth browser detected. Please consider using MetaMask.");
    }
  };

合约/PaymentToken.sol

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract PaymentToken is ERC20 {
    address public owner;

    constructor() ERC20("Payment Token", "Pay") {
        owner = msg.sender;
        _mint(msg.sender, 100000 * 10**18);
    }

    function mint(address to, uint256 amount) external {
        require(msg.sender == owner, "Only owner can mint");
        _mint(to, amount);
    }
}
reactjs solidity smartcontracts truffle decentralized-applications
1个回答
0
投票

因为这里的

networkId
类型

 const networkId = await web3.eth.net.getId();

bigInt
。 TypeScript 不允许直接将
bigint
用作索引类型。在将其用作索引之前,您需要将 bigint 转换为字符串或数字。 来自 Mdn 文档

const networkId = await web3.eth.net.getId();

// Convert networkId to string
const networkIdStr = networkId.toString();

现在你应该被允许了:

 const paymentTokenData = PaymentToken.networks[networkIdStr];
© www.soinside.com 2019 - 2024. All rights reserved.