0

I am using Truffle to deploy a contract on Ganache and retrieve the contract in an express app. While I can get the contract instance and it can console.log a list of function object, the function cannot be called in the code.

Here is my contract:

contract Vote{
    uint dem = 0;
    uint pub = 0;

    constructor() public {
        dem = 0;
        pub = 0;
    }

    function vote(uint v) public {
        if(v == 1){
            pub += 1;
        } else {
            dem += 1;
        }
    }

    function getWinner() public view returns (uint) {
        if(dem > pub){
            return dem;
        } else {
            return 0 - pub;
        }
    }
}

Code call the function:

var voteAbi = [{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"constant":false,"inputs":[],"name":"getWinner","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256[]","name":"v","type":"uint256[]"}],"name":"vote","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
web3.eth.defaultAccount = web3.eth.accounts[0]
web3.personal.unlockAccount(web3.eth.defaultAccount)
var voteContract = web3.eth.contract(voteAbi);
var voteInstance = voteContract.at("0x0711217536458a37580e669de781554ce33236c24711d351d446a437e16ae058");
voteInstance.vote.call(1)
voteInstance.vote(1)
voteInstance.vote.sendTransaction(1,{from:web3.eth.accounts[0]})

All the three lines call the function vote result in the Foreach problem. I am new to web3 and blockchain! Any ideas on what could go wrong here?

5
  • 1
    What is the version of your web3? – Masoud jt Nov 30 '20 at 6:36
  • You need to put those lines in an async function, and add await in some of them (the last 3 for sure, the one before them if your web3.js version is 1 or higher). – goodvibration Nov 30 '20 at 6:43
  • in addition to what @goodvibration said. you need to change web3.eth.contract(voteAbi) to web3.eth.Contract(voteAbi) in web3 version 1 or higher. (notice that Contract has a capital C ) – Masoud jt Nov 30 '20 at 8:12
  • @Masoudjt: You're wrong about the await. This is just the creation of a local web3.eth.Contract object. There is no interaction with the remote node here, hence no need to asynchronously await for it to complete. – goodvibration Nov 30 '20 at 8:13
  • @goodvibration yes. thanks. edited. – Masoud jt Nov 30 '20 at 8:14
0

It is a problem caused by Truffle. When I move to remix and deploy the contract in my ganache-cli, it works.

1
  • Don’t unlock accounts, better to sign the transactions with the private key. – Majd TL Mar 12 at 8:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.