简体   繁体   中英

Call Function From Solidity With Web3

I am having trouble calling a simple function from my solidity contract. Here's how the code is structured so far:

In my web3Api.js file I have:

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();
}

Then in my projectApi.js file I have:

import { getContract } from './web3Api';
import CompiledContract '../../../build/contracts/compiledContract.json';

let globalVariable;

export async function testing123() {
  const contractInstance = await getContract(CompiledContract)
  globalVariable = contractInstance;
}

Note: When I call the global variable throughout this file it successfully returns all my contract's functions

TruffleContract {constructor: ƒ, abi: Array(33), contract: Contract, PracticeEvent: ƒ, Transfer: ƒ, …}

So this next part is where I'm running into trouble.

For this post's sake, I am just trying to call this simple function from my contract:

function smartContractFunction() public {
    emit PracticeEvent("practice event has been called");
}

Now back in my projectApi.js file I am using the globalVariable to try grab this function from my contract. Here's what I wrote:

export async function practiceInteract() {
   const submitTest = await globalVariable.smartContractFunction().call();
   console.log(submitTest);
}

When I run the app I get an error saying "formatters.js:274 Uncaught (in promise) Error: invalid address"

Any ideas why I cannot call this solidity function in my projectAPI.js file?

Happy to clarify this if I did not clearly write out my problem. Thank You!

Your issue is that your are simply not defining an address that is calling the function. You need to defined who is calling the function if you are using web3 in the manner that you are. The correct code would be:

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

You can do it like this:

const contract = new web3.eth.Contract(ABI, address)
const returnValue = await contract.methods.someFunc(someArg).call()

For more information about how to interact with smart contracts using web3.js, read this article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM