Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
dzarezenko opened this issue Oct 3, 2017 · 69 comments
Closed

Comments

@dzarezenko
Copy link

dzarezenko commented Oct 3, 2017

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);
    });
}
@sponnet
Copy link

sponnet commented Oct 5, 2017

I also received this bug - upgrading to ^1.0.0-beta.22 fixed this for me.

@thackerronak
Copy link

Same issue facing in "web3": "^1.0.0-beta.23",
this.contractObj.methods.balanceOf(address).call(function (err, wieBalance) {}

Error: Couldn't decode uint256 from ABI: 0x
    at SolidityTypeUInt.formatOutputUInt [as _outputFormatter] (formatters.js:162)
    at SolidityTypeUInt.webpackJsonp.../../../../web3-eth-abi/src/type.js.SolidityType.decode (type.js:252)
    at index.js:327
    at Array.forEach (<anonymous>)
    at ABICoder.webpackJsonp.../../../../web3-eth-abi/src/index.js.ABICoder.decodeParameters (index.js:326)
    at Contract.webpackJsonp.../../../../web3-eth-contract/src/index.js.Contract._decodeMethodReturn (index.js:451)
    at Method.outputFormatter (index.js:798)
    at Method.webpackJsonp.../../../../web3-core-method/src/index.js.Method.formatOutput (index.js:162)
    at sendTxCallback (index.js:453)
    at index.js:144
    at XMLHttpRequest.request.onreadystatechange [as __zone_symbol__ON_PROPERTYreadystatechange] (index.js:64)
    at XMLHttpRequest.wrapFn (zone.js:1166)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:425)
    at Object.onInvokeTask (core.es5.js:3881)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (zone.js:192)
    at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:499)
    at invokeTask (zone.js:1540)
    at XMLHttpRequest.globalZoneAwareCallback (zone.js:1566)

@thackerronak
Copy link

also tried with ^1.0.0-beta.22 but issue remains same

@jacobsimon
Copy link

Hey all, I was also receiving this bug and it turned out to be a slight difference in the ABI of my contract and the one I was using in my application. Not sure if there's another cause, but I would make sure that you're using the most recent version of your contract's ABI.

@skiral
Copy link

skiral commented Oct 15, 2017

We are getting the same issue, only on Ropsten testnet

@guptapriyank
Copy link

no luck yet, anybody have a solution, please list

@dzarezenko
Copy link
Author

dzarezenko commented Oct 23, 2017

I have resolved this with enclosing functionality into Promise:

_getTokenBalance : function (address) {
        var _this = this;
        return new Promise(function(resolve, reject) {
            var tokenBalance = 0;
            _this.contract.methods.balanceOf(address).call().then(function (result) {
                var tokensWei = result;
                console.log("Tokens Wei: " + tokensWei);
                _this.contract.methods.decimals().call().then(function (result) {
                    var decimals = result;
                    console.log("Token decimals: " + decimals);

                    tokenBalance = parseFloat(tokensWei) / Math.pow(10, decimals);
                    console.log("Token balance: " + tokenBalance);

                    resolve(tokenBalance);
                });
            });
        });
    }

and call it like:

this._getTokenBalance(address).then(function(tokenBalance) {
    // ...
});

@jdkanani
Copy link
Contributor

jdkanani commented Nov 6, 2017

For now, you can use -

web3.eth.call({
    to: address,
    data: contract.methods.balanceOf(address).encodeABI()
}).then(balance => {})

@lionello
Copy link
Contributor

I disagree with the fix that was introduced in 15ffd55. This should not be handled by such low-level conversion code.

@frozeman
Copy link
Contributor

So to understand that right, the contract returns 0x? If so then this is certainly not a good fix, and i changed it in develop to make sure 0x will fail.

@frozeman
Copy link
Contributor

frozeman commented Dec 13, 2017

@lionello you are right. Its actually wrong behaviour.
So if it would return 0 the value would look like:

> web3.eth.call({to: '0x6d72f4097b093518114ac0ba54d7c9fd73eecc05', data: '0x39f6ca500000000000000000000000000000000000000000000000000000000000000000'})
"0x0000000000000000000000000000000000000000000000000000000000000000"

Though if it throws, it looks like:

> web3.eth.call({to: '0x4597b8c3b40d96dc0365ced9dc9b56b81247120d', data: '0x39f6ca500000000000000000000000000000000000000000000000000000000000000000'})
"0x"

Therefore the raw value is also empty if it failed. This is a problem of how the token contract is build and not one of web3.js

So you need to catch the errors of the call, as it throws inside the contract, rather then returning anything expected.

frozeman added a commit that referenced this issue Dec 13, 2017
@lionello
Copy link
Contributor

@frozeman Yeah, that's more like it.

I'd really like to see some test that warrants the !param.rawValue clauses you've added. For the current tests, those clauses don't appear to changes the behavior at all, suggesting that they might be superfluous.

@frozeman
Copy link
Contributor

I added the !param.rawValue only for int, uint and bool, as here we don't want it to be accidentally interpreted as 0, or false

@mobilesite
Copy link

same error in version 1.0-beta.28. How to solve it?

@MRHarrison
Copy link

same error in version 1.0-beta.29. Anybody figure this out yet?

@dgrant069
Copy link

dgrant069 commented Feb 9, 2018

I was getting this with beta.26. I figured out that my deployed and compiled contracts were out of sync and that I was calling a function in my contract that didn't exist in the old contract. In other words, I made a change to my contract, compiled and deployed. I hadn't updated the address to my deployed contract (which I used to created instances of another contract that in my web ui was something like "add new "). Once I updated the address, refreshed, and created a new instance through my browser, it worked.

@faizan-ali
Copy link

faizan-ali commented Feb 13, 2018

Started getting this error today in beta.29 after I updated my locally deployed Smart Contract with a constructor (it previously had none)
Calling any constant function causes the error, other functions work fine. Would very much appreciate some insight.
Updating to beta.30 did not help

@jamboj
Copy link

jamboj commented Feb 20, 2018

Same here... calling a const contract method with web3js 1.0.0-beta.30 intermittently triggers:

Error: Couldn't decode uint256 from ABI: 0x
    at SolidityTypeUInt.formatOutputUInt [as _outputFormatter] (/Users/tu/node_modules/web3-eth-abi/src/formatters.js:174:15)
    at SolidityTypeUInt.SolidityType.decode (/Users/tu/node_modules/web3-eth-abi/src/type.js:252:17)
    at /Users/tu/node_modules/web3-eth-abi/src/index.js:327:49
    at Array.forEach (<anonymous>)
    at ABICoder.decodeParameters (/Users/tu/node_modules/web3-eth-abi/src/index.js:326:13)
    at Contract._decodeMethodReturn (/Users/tu/node_modules/web3-eth-contract/src/index.js:459:22)
    at Method.outputFormatter (/Users/tu/node_modules/web3-eth-contract/src/index.js:811:46)
    at Method.formatOutput (/Users/tu/node_modules/web3-core-method/src/index.js:162:54)
    at sendTxCallback (/Users/tu/node_modules/web3-core-method/src/index.js:453:33)
    at Object.<anonymous> (/Users/tu/node_modules/web3-core-requestmanager/src/index.js:144:9)
    at /Users/tu/node_modules/web3-providers-ws/src/index.js:76:44
    at Array.forEach (<anonymous>)
    at W3CWebSocket.WebsocketProvider.connection.onmessage (/Users/tu/node_modules/web3-providers-ws/src/index.js:53:36)
    at W3CWebSocket._dispatchEvent [as dispatchEvent] (/Users/tu/node_modules/yaeti/lib/EventTarget.js:107:17)
    at W3CWebSocket.onMessage (/Users/tu/node_modules/websocket/lib/W3CWebSocket.js:234:14)
    at WebSocketConnection.<anonymous> (/Users/tu/node_modules/websocket/lib/W3CWebSocket.js:205:19)
    at WebSocketConnection.emit (events.js:160:13)
    at WebSocketConnection.processFrame (/Users/tu/node_modules/websocket/lib/WebSocketConnection.js:547:26)
    at /Users/tu/node_modules/websocket/lib/WebSocketConnection.js:321:40
    at process._tickCallback (internal/process/next_tick.js:150:11)

@TrejGun
Copy link

TrejGun commented Feb 22, 2018

same here

1 similar comment
@akucheruk-vareger
Copy link

same here

@srameshr
Copy link

srameshr commented Mar 3, 2018

This still remains :(

@haydenadams
Copy link

Did this never get fixed? Still getting it in beta 33...

@mustafakemal16
Copy link

same here! Latest version: 1.0.0-beta.33

1 similar comment
@VulgarnyKarlson
Copy link

same here! Latest version: 1.0.0-beta.33

@quantumproducer
Copy link

@SlaAls I don't want to mine, I just want to use geth to read from transactions. I tried miner.start() then running my code, same issue.

@Aniket-Engg
Copy link

Aniket-Engg commented May 18, 2018

facing this problem in web3 version 1.0.0-beta.34 with metamask & Ropsten
Does anyone have a proper solution?

@k06a
Copy link

k06a commented May 20, 2018

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

@drewstaylor
Copy link

drewstaylor commented May 23, 2018

I have this issue on Kovan at the moment and I can confirm I am using the correct ABI. I have recompiled it so many times, and I always get the same result. I also deployed my contract in web3 in the same closure and I still can't call the method.

@drewstaylor
Copy link

After some review, I seem to have been having an issue similar to @SlaAls I didn't realize my Kovan node had stopped silently syncing. Although I could see the transaction on Etherscan, I didn't have the block yet.

@barakman
Copy link
Contributor

barakman commented Jun 6, 2018

Same problem when working with Parity (on a local host).

However, this seems to be due to an incorrect usage of Web3, and I was able to resolve it as follows:

First, I added these two helper functions:

async function call(transaction) {
    let success = await web3.eth.personal.unlockAccount(OWNER_ADDRESS, OWNER_PASSWORD);
    let gas = await transaction.estimateGas({from: OWNER_ADDRESS, gasPrice: GAS_PRICE});
    return await transaction.call({from: OWNER_ADDRESS, gasPrice: GAS_PRICE, gas: gas});
}

async function send(transaction) {
    let success = await web3.eth.personal.unlockAccount(OWNER_ADDRESS, OWNER_PASSWORD);
    let gas = await transaction.estimateGas({from: OWNER_ADDRESS, gasPrice: GAS_PRICE});
    return await transaction.send({from: OWNER_ADDRESS, gasPrice: GAS_PRICE, gas: gas});
}

Then, in order to invoke an onchain-stateless function, I use:

await call(myContract.methods.myMethod(put your args here if needed));

And in order to invoke an onchain-stateful function, I use:

await send(myContract.methods.myMethod(put your args here if needed));

Of course, in the helper functions, you may get rid of the unlockAccount part and / or the estimateGas part if they are not necessary for your system behavior requirements.

@fritzmatias
Copy link

fritzmatias commented Jul 2, 2018

i found the same problem, but was because the address of the contract was wrong.
So, for me the real issue is "an invalid contract can be mapped to an object without throw an exception". Then, when you try to call the method the exception is throwed.

    "web3": "^1.0.0-beta.34",
    "web3-core-requestmanager": "^1.0.0-beta.34",
    "web3-eth": "^1.0.0-beta.34",
    "web3-eth-contract": "^1.0.0-beta.34"

@ramxis
Copy link

ramxis commented Jul 10, 2018

I am having the same issue, My dapp is using infura ropsten node as geth provider, Its a Nodejs app, and I have triple checked my Contract ABI and address, If i downgrade to Web3 0.20 i do not see this error with the same provider, and setup. I only encounter this problem if i use web 1.0

@zhouxbalabala
Copy link

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

VWoeltjen added a commit to VWoeltjen/beekeeper that referenced this issue Aug 1, 2018
@leavesgreen
Copy link

leavesgreen commented Aug 4, 2018

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
Copy link

disadone commented Sep 6, 2018

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

@antonpegov
Copy link

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

@yzhang1994
Copy link

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
Copy link

xoxoj commented Nov 29, 2018

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

@k06a
Copy link

k06a commented Nov 29, 2018

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

@xoxoj
Copy link

xoxoj commented Nov 29, 2018

@k06a I am sure it has

@Pupin3
Copy link

Pupin3 commented Dec 8, 2018

Any ideas on how to resolve this issue would be highly appreciated...
I am using [email protected] 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
Copy link

What is contract.images ?

@Pupin3
Copy link

Pupin3 commented Dec 10, 2018

@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
Copy link

vauvenal5 commented Feb 3, 2019

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 [email protected]. 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
Copy link

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
Copy link

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
Copy link

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

@surendersinghIT
Copy link

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!

nachomazzara pushed a commit to nachomazzara/web3.js that referenced this issue Jun 4, 2020
nachomazzara pushed a commit to nachomazzara/web3.js that referenced this issue Jun 4, 2020
@razik-r
Copy link

razik-r commented Oct 8, 2022

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
Copy link
Contributor

barakman commented Oct 8, 2022

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

@razik-r
Copy link

razik-r commented Oct 9, 2022

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'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests