web3 / web3.js

Collection of comprehensive TypeScript libraries for Interaction with the Ethereum JSON RPC API and utility functions.
https://web3js.org/
Other
19.19k stars 4.92k forks source link

TypeError: token.methods.balanceOf(...).call(...).on is not a function #1089

Closed dzarezenko closed 6 years ago

dzarezenko commented 6 years ago

Hi,

I am trying to get ERC20 tokens balance on some address with web3.js lib but received this error:

Unhandled rejection Error: Couldn't decode uint256 from ABI: 0x
    at SolidityTypeUInt.formatOutputUInt (...\node_modules\web3-eth-abi\src\formatters.js:176:15)
    at SolidityTypeUInt.SolidityType.decode (...\node_modules\web3-eth-abi\src\type.js:252:17)
    at ...\node_modules\web3-eth-abi\src\index.js:327:49
    at Array.forEach (native)
    at ABICoder.decodeParameters (...\node_modules\web3-eth-abi\src\index.js:326:13)
    at Contract._decodeMethodReturn (...\node_modules\web3-eth-contract\src\index.js:451:22)
    at Method.outputFormatter (...\node_modules\web3-eth-contract\src\index.js:798:46)
    at Method.formatOutput (...\node_modules\web3-core-method\src\index.js:162:54)
    at sendTxCallback (...\node_modules\web3-core-method\src\index.js:453:33)
    at ...\node_modules\web3-core-requestmanager\src\index.js:144:9
    at XMLHttpRequest.request.onreadystatechange (...\node_modules\web3-providers-http\src\index.js:64:13)
    at XMLHttpRequestEventTarget.dispatchEvent (...\node_modules\xhr2\lib\xhr2.js:64:18)
    at XMLHttpRequest._setReadyState (...\node_modules\xhr2\lib\xhr2.js:354:12)
    at XMLHttpRequest._onHttpResponseEnd (...\node_modules\xhr2\lib\xhr2.js:509:12)
    at IncomingMessage.<anonymous> (...\node_modules\xhr2\lib\xhr2.js:469:24)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)

My code:

var getTokenBalance = function(address) {
    var token = new web3.eth.Contract(contract_data.abi, contract_data.TOKEN_CONTRACT_ADDRESS);
    token.methods.balanceOf(address).call().then(function (result) {
        console.log(result);
    });
}
zhouxbalabala commented 6 years ago

Maybe the network environment of your plugin is not synchronized with your contract. Try switching.

leavesgreen commented 6 years ago

1.0.0-beta.35 , same issue, and sth more wired that at the begining the code runing correctly , but after I install another package keythereum , all codes about contract get the error

then I deploy a new contract with the same code , and everything goes ok this time.

disadone commented 6 years ago

Hey ,em...... ,is this problem solved? is there a solution?

antonpegov commented 5 years ago

Double check the abi. I've got this 'bug' after minor changes in contract code without updating the abi.

yzhang1994 commented 5 years ago

One possibility is that the blockchain node Metamask uses is corrupt / has false data. Found that error in my dapp today (metamask mainnet node) and it was causing the lookup of one constant .call() to fail about 5% of the time. The issue was fixed after switching metamask network to Custom RPC and connected it to a node that I myself am hosting, and the issue disappeared.

xoxoj commented 5 years ago

version 1.0.0-beta.33 still has this problem. Anyone has already solved this problem?

k06a commented 5 years ago

@xoxoj this problem means you try to call the method of a contract which is not existing on this address.

xoxoj commented 5 years ago

@k06a I am sure it has

Pupin3 commented 5 years ago

Any ideas on how to resolve this issue would be highly appreciated... I am using web3@1.0.0-beta.37 on windows7 Truffle v4.1.14 npm: '6.4.1'. Ganache is running and my app works fine. However, if I use .call() I get the error "contract.images(...).call is not a function"

quantumproducer commented 5 years ago

What is contract.images ?

Pupin3 commented 5 years ago

@quantumproducer thank you for your answer. You were right, I was mistakenly calling "images" which is an array and not a function. I figured it out soon after posting my previous message.

vauvenal5 commented 5 years ago

I have the same behavior like @dacarley had. Sometimes it works and sometimes it does not. Interestingly enough, it just started appearing without any obvious reason.

The first thing I tried is to run a local geth node instead of using the Infura API, this did not change anything. My local geth node is running in light mode.

I also reverted my code base to the state when I deployed the contracts originally to make sure I am using the ABI as deployed.

I was calling some functions on my contracts that modify the state before all started and to be honest at this point it might have been that my ABIs we're not entirely correct however since the functions finished without error I assume it should be fine. Furthermore, as mentioned sometimes I am able to read the data from the contract so it is on chain.

I am by now at the point to simply try and redeploy everything to see if the behavior goes way.

I am working on the Ropsten network and currently running web3@1.0.0-beta.34. Open for any suggestions.

Edit: The behavior is the same with Metamask in the web browser as with my own client that uses a HttpProvider.

felixwatts commented 5 years ago

I have the same problem. ABI is definitely in sync with deployed contract. web3-provider-engine, HttpProvider, ganache-cli, embark. Started seemingly randomly today and occurs seemingly unpredictably. I get it when calling contract.getPastEvents (there are no events in the log that match the type)

felixwatts commented 5 years ago

OK, I was able to fix by specifying a from address when calling contract.getPastEvents:

const stateEvents = await Atl.getPastEvents('EventName', {
    filter: {a: b},
    fromBlock: 0,
    toBlock: 'latest',
}, { from: fromAddress });
felixwatts commented 5 years ago

Sorry that was wrong. It just randomly worked a couple fo times then started failing again

surendersinghIT commented 5 years ago

I were receiving same error and finally, I were able to fix issue as per following.

  1. const Election = new web3.eth.Contract(abi, contractAddress, { from: web3.eth.defaultAccount }); I were using incorrect contract address

  2. web3.eth.getTransactionCount(address, function (err, nonce) {
    const functionAbi = Election.methods.mymethod().encodeABI();

    var details = {
        'nonce': nonce,
        'gasPrice': web3.utils.toHex(web3.utils.toWei('20', 'gwei')),
        'gas': 6721975,
        'from': address,
        'to': contractAddress,
        'value': 0,
        'data': functionAbi,
    };
    const transaction = new EthereumTx(details);
    transaction.sign(Buffer.from(pk, 'hex') )
    var rawData = '0x' + transaction.serialize().toString('hex');
    console.log(rawData);
    web3.eth.sendSignedTransaction(rawData)
    .on('transactionHash', function(hash){
        console.log(['transferToStaging Trx Hash:' + hash]);
    })
    .on('receipt', function(receipt){
        console.log(['transferToStaging Receipt:', receipt]);
        res.send(receipt);
    })
    .on('error', console.error);

    });

i were using incorrect contract address in 'to' field of details of transaction.

I corrected contract address at both places and code worked correctly. I hope it would be helpful for someone.

Happy Coding!

razik-r commented 1 year ago

got this error : Unhandled Rejection (TypeError): token.methods.balanceOf is not a function when i was trying to load tokenbalance as javascript version of the token smart contract

here is my code : const token = new web3.eth.Contract(Token.abi, tokenData.address) this.setState({ token }) let tokenBalance = await token.methods.balanceOf(this.state.account).call() this.setState({ tokenBalance: tokenBalance.toString() })

barakman commented 1 year ago

@razik-r : your Token.abi is probably wrong.

razik-r commented 1 year ago

oh my god ..tkysm !! I was trying to solve the problem like 6 hours so what happened is that when I imported the token contract and other contract I made some typo errors

I did this import EthSwap from '../abis/EthSwap.json' import Token from '../abis/EthSwap.json'

instead of this : import EthSwap from '../abis/EthSwap.json' import Token from '../abis/Token.json'