【问题标题】:Querying Smart Contract using its ABI and Ether.js in React在 React 中使用其 ABI 和 Ether.js 查询智能合约
【发布时间】:2022-10-01 08:03:41
【问题描述】:

我有一个部署到主网的合同。我有一个导出函数的 javascript 文件,以便其他文件可以调用它们。我有一个按钮,可以根据我的反应调用getOwnerOfToken。当我单击该按钮时,没有任何反应,也没有记录任何内容。我了解,由于这是一种只读视图方法,因此我只需要提供程序(元掩码)。在访问应用程序之前,我验证了用户,以便使用window.ethereum 检测到元掩码。

// Gallery.js (a react component)
import React from \"react\";
import { getOwnerOfToken } from \"../services/nftcontract\";

class Gallery extends React.Component {
  constructor(props){
     //constructor stuff here
  }


  // called by onClick of a button in react
  handleProfileChange = selected(selectedIndex) => {
      getOwnerOfToken(selectedIndex).then((address) => {
      this.setState({ currentSelectionnOwner: address });
      console.log(this.state.currentSelectionnOwner);
     });
   }

  render() { 
      // a button with the callback attached to onclick
      <button onClick=onClick={() => this.handleProfileChange ()}>Change Profile</button>
  }
}

这是上面导入的 service/nftcontract.js 文件

import { ethers } from \"ethers\";

// Note: the full abi was copied from the ABI section found in etherscan. 
// This is a simplified version for this example
const abi = [
  {
    inputs: [{ internalType: \"uint256\", name: \"tokenId\", type: \"uint256\" }],
    name: \"ownerOf\",
    outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],
    stateMutability: \"view\",
    type: \"function\",
  },
];

const provider = new ethers.providers.Web3Provider(window.ethereum);
const address = global.config.addresses.collections.genesis;
const contract = new ethers.Contract(address, abi, provider);

const getOwnerOfToken = async (tokenid) => {
  return await contract.ownerOf(tokenid);
};

export { getOwnerOfToken };

    标签: reactjs smartcontracts abi ethers.js


    【解决方案1】:

    您应该像这样在provider 上调用getSigner()

    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const address = global.config.addresses.collections.genesis;
    const contract = new ethers.Contract(address, abi, signer);
    

    getSigner() 来自官方文档

    返回由该以太坊节点管理的 JsonRpcSigner,地址为地址或索引。如果未提供 addressOrIndex,则使用第一个帐户(帐户 #0)。 你可以在这里阅读它https://docs.ethers.io/v5/api/providers/jsonrpc-provider/

    另外,请确保您在ethers.contract 中传递正确的地址

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-19
      • 2023-02-07
      • 2022-08-23
      • 1970-01-01
      • 2022-12-06
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多