首页 > 解决方案 > Solidity问题将参数传递给函数

问题描述

我有一个具有以下功能的智能合约:

contract Example {
     event claimed(address owner);
     function claimStar() public {
          owner = msg.sender;
          emit claimed(msg.sender);
     }
}

我使用 Truffle V5.0 和 Webpack box 作为样板代码。

在我的truffle-config.js文件中,我有网络配置:

development:{
  host:"127.0.0.1",
  port: 9545,
  network_id:"*"
}

一切都可以使用: - truffle develop - compile -migrate --reset 它说Truffle Develop started at http://127.0.0.1:9545

在我的 index.js 文件中,我有以下代码:

import Web3 from "web3";
import starNotaryArtifact from "../../build/contracts/StarNotary.json";

const App = {
  web3: null,
  account: null,
  meta: null,

  start: async function() {
    const { web3 } = this;

    try {
      // get contract instance
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = starNotaryArtifact.networks[networkId];
      this.meta = new web3.eth.Contract(
        starNotaryArtifact.abi,
        deployedNetwork.address,
      );

      // get accounts
      const accounts = await web3.eth.getAccounts();
      this.account = accounts[0];
    } catch (error) {
      console.error("Could not connect to contract or chain.");
    }
  },

  setStatus: function(message) {
    const status = document.getElementById("status");
    status.innerHTML = message;
  },

  claimStarFunc: async function(){
    const { claimStar } = this.meta.methods;
    await claimStar();
    App.setStatus("New Star Owner is " + this.account + ".");
  }

};

window.App = App;

window.addEventListener("load", async function() {
  if (window.ethereum) {
    // use MetaMask's provider
    App.web3 = new Web3(window.ethereum);
    await window.ethereum.enable(); // get permission to access accounts
  } else {
    console.warn("No web3 detected. Falling back to http://127.0.0.1:9545. You should remove this fallback when you deploy live",);
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    App.web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:9545"),);
  }

  App.start();
});

在我的浏览器中,我安装了 Metamask,我添加了一个具有相同 URL 的专用网络,还导入了两个帐户。当我启动应用程序并在浏览器中打开它时,它会打开 Metamask 以请求权限,因为我正在使用window.ethereum.enable();. 但是当我点击按钮时,claim它什么也没做。正常行为是 Metamask 打开提示要求确认,但它从未发生。我还在合同中创建了一个新属性进行测试,它可以很好地显示合同构造函数中分配的值。我的问题是,我错过了什么吗?

我也尝试将函数更改为await claimStar();await claimStar({from: this.account});但在这种情况下,我收到一个错误,说claimStar不需要参数。

我将不胜感激任何帮助。谢谢

标签: soliditytrufflemetamask

解决方案


我解决了这个问题,问题出在函数中claimStarFunc 应该是这样的:

claimStarFunc: async function(){
    const { claimStar } = this.meta.methods;
    await claimStar().send({from:this.account});
    App.setStatus("New Star Owner is " + this.account + ".");
  }

因为我正在发送交易。谢谢


推荐阅读