1

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: ƒ, …} 

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?

1
  • Can you check that the contract address is correct and actually points to your contract? Commented Oct 29, 2018 at 13:21

2 Answers 2

1

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.js 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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

This is not necessary when you call a function. It is necessary only when you send a transaction. You can read more about it on the documentation: web3js.readthedocs.io/en/1.0/web3-eth-contract.html
0

You can do it like this:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.