Skip to content
Advertisement

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!

Advertisement

Answer

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);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement