Javascript 使用Web3从Solidity调用函数

Javascript 使用Web3从Solidity调用函数,javascript,ethereum,solidity,web3,truffle,Javascript,Ethereum,Solidity,Web3,Truffle,我在从solidity合约调用简单函数时遇到问题。以下是迄今为止代码的结构: 在我的web3Api.js文件中,我有: export function getContract(contractDefinition) { initWeb3(); const contract = initContract(contractDefinition); contract.setProvider(web3.currentProvider); if (typeof contract.currentP

我在从solidity合约调用简单函数时遇到问题。以下是迄今为止代码的结构:

在我的
web3Api.js
文件中,我有:

export function getContract(contractDefinition) {
 initWeb3();
 const contract = initContract(contractDefinition);
 contract.setProvider(web3.currentProvider);

 if (typeof contract.currentProvider.sendAsync !== 'function') {
    contract.currentProvider.sendAsync = function () {
      return contract.currentProvider.send.apply(
         contract.currentProvider, arguments
      );
    };
  }
 return contract.deployed();
}
import { getContract } from './web3Api';
import CompiledContract '../../../build/contracts/compiledContract.json';

let globalVariable;

export async function testing123() {
  const contractInstance = await getContract(CompiledContract)
  globalVariable = contractInstance;
}
然后在我的
projectApi.js
文件中,我有:

export function getContract(contractDefinition) {
 initWeb3();
 const contract = initContract(contractDefinition);
 contract.setProvider(web3.currentProvider);

 if (typeof contract.currentProvider.sendAsync !== 'function') {
    contract.currentProvider.sendAsync = function () {
      return contract.currentProvider.send.apply(
         contract.currentProvider, arguments
      );
    };
  }
 return contract.deployed();
}
import { getContract } from './web3Api';
import CompiledContract '../../../build/contracts/compiledContract.json';

let globalVariable;

export async function testing123() {
  const contractInstance = await getContract(CompiledContract)
  globalVariable = contractInstance;
}
注意:当我在整个文件中调用全局变量时,它会成功地返回我的所有契约函数

TruffleContract {constructor: ƒ, abi: Array(33), contract: Contract, PracticeEvent: ƒ, Transfer: ƒ, …}
所以下一部分就是我遇到麻烦的地方

为了这篇文章,我只是想从我的合同中调用这个简单的函数:

function smartContractFunction() public {
    emit PracticeEvent("practice event has been called");
}
现在回到我的
projectApi.js
文件中,我正在使用globalVariable从我的合同中获取这个函数。以下是我写的:

export async function practiceInteract() {
   const submitTest = await globalVariable.smartContractFunction().call();
   console.log(submitTest);
}
当我运行应用程序时,我收到一个错误,上面写着“formatters.js:274 Uncaught(in promise)error:invalid address”

你知道为什么我不能在projectAPI.js文件中调用这个solidity函数吗

如果我没有清楚地写出我的问题,我很乐意澄清这一点。
谢谢大家!

您的问题在于,您没有定义调用函数的地址。如果您使用的是
web3
,则需要定义调用函数的用户。正确的代码是:

export async function practiceInteract() {
   const submitTest = await globalVariable.smartContractFunction().call({from: web3.eth.accounts[0]});
   console.log(submitTest);
}

当调用函数时,这不是必需的。仅当您发送
事务时才需要此选项。您可以在文档中了解更多信息:您是否可以检查合同地址是否正确并实际指向您的合同?