Solvedweb3.js TypeError: token.methods.balanceOf(...).call(...).on is not a function


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) {
51 Answers

βœ”οΈAccepted Answer

For now, you can use -{
    to: address,
    data: contract.methods.balanceOf(address).encodeABI()
}).then(balance => {})

Other Answers:

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)

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

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

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);


and call it like:

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

Related Issues:

web3.js sendSignedTransaction() error: invalid sender
@paulrberg If you want to use the version: 2.0.0 you should add extra parameter chain like this ...
web3.js The method personal_unlockAccount does not exist/is not available
@vijayr2410 Well Looks like it's just require to specify following parameters to resolve this issue ...
web3.js Handle web socket disconnects
You can listen to events from the WebSocketProvider to detect disconnects. Im making an app that mon...
web3.js Transferring ERC20 tokens from account using web3 over Ropsten
Single-address allocation of MineFIL Token (MFIL) code which was written and tested using web3 versi...
web3.js Error: Can't resolve 'crypto'
Ah yes!! this solution with the patch worked:
web3.js Truffle and Ganache providers, Metamask Provider Engine no longer accepted as valid by web3
For those who might not know me I'm part of the Truffle team and @davidmurdoch and I oversee the dev...
web3.js Transaction was not mined within 50 blocks, please make sure your transaction was properly send. Be aware that it might still be mined!
I think I found the error When I call a contract function and await the send startWatching is invoke...
web3.js Angular hack with node: {crypto: true} doesn't work anymore in Angular 12
@NicolasKritter Thanks for sharing your solution I've fixed the process and Buffer errors the way yo...
web3.js Unable to install web3 1.0.0-beta.11 or web3 1.0.0-beta.12
@1337cookie try installing v0.20.0 or downgrading node to v6: or Hi I'm using node 8.2.1 and npm 5.3...
web3.js Unable to install web3 on windows10
$npm install web3@^0.20.0 worked for me Issue solved on #950 C:>npm install -g web3 web3@1.0.0-beta....
web3.js web3.currentProvider.sendAsync is undefined
try to add before create new instance: Web3.providers.HttpProvider.prototype.sendAsync = Web3.provid...
web3.js Web3.js returns "Cannot find module 'web3-requestManager'"
The same thing after npm update web3 updates to web3@1.0.0-beta2 instead of current web3@1.0.0-beta3...
web3.js TypeError: token.methods.balanceOf(...).call(...).on is not a function
For now you can use - Hi I am trying to get ERC20 tokens balance on some address with web3.js lib bu...
web3.js getTransactionCount() returns incorrect nonce when transactions are pending
I believe you can call web3.eth.getTransactionCount(address 'pending') to include pending transactio...
web3.js Bignumber issue in web3 invalid number value (arg="_value", coderType="uint256", value=10000000000000000)
Heads up 2021 still remains a issue. Getting invalid number error when calling a method of a contrac...
web3.js Cannot find name 'Buffer'. Can't find module 'net'.
ahhh i think i found your issue Expected behavior Ionic/Angular handles the Web3 import fine and ser...
neovim build fails with OSX Mojave
Starting with Mojave the headers are no longer installed under /usr/include/ by default -- look unde...
graphql engine relay support
Hi @srghma @toxsick relay makes assumptions about the GraphQL server as outlined here We haven't mad...
amplify cli Many-To-Many
You can implement many to many yourself using two 1-M @connections and a joining @model ...
zeal Content rendering error in MDN (HTML, JS, CSS) docsets
I find it can fix temporary by remove the CSS.docset\Contents\Resources\Documents\developer.mozilla....
type graphql Getting "Schema must contain uniquely named types but contains multiple types named" for a single type
This was a hard one to track down with an annoying fix (Nest specific not the fault of type-graphql)...
axios module How to set query params and message body?
No I don't mean the baseURL but the url path As an example let's say I have the following call: Axio...
strapi πŸ‘‰ Question: What are the main pain points you have using Strapi? (Episode 3)
Pain point Issue: No TypeScript support Context: I know it has been mentioned as something the team ...
fastapi WARNING: Unsupported upgrade request.
This error is not part of the FastAPI codebase When attempting to run this (using UviCorn) it starts...
neovim Build failed with Homebrew on both macOS 11.4 and 12.0.1
This should be fixed in Homebrew for now Neovim version (nvim -v) Upgrading neovim HEAD-487286b -> H...
amplify cli aws-exports.js is not generated
Even after the third read I find it utterly confusing and I have usability issues too ...
fastapi [QUESTION] How to bridge Pydantic models with SQLAlchemy?
I just finished integrating Pydantic ORM mode into FastAPI it is released as version 0.30.0 πŸŽ‰ The n...
strapi New project fails to connect to database
I had the same issue with 3.0.0-alpha.10 I ran strapi new project-name then when it prompts to enter...
ponzu no go files in /home/user/go/src/
try running go get -u via copy / paste that exact command. ...
amplify cli @auth public/private IAM roles and other Providers
ok my bad was actually quite easy just do : and add a auth provider in my case was IAM ...
neovim Update tree-sitter to v0.19.0
Workaround for homebrew users: Uninstall tree-sitter@0.19.1 ignoring neovim dependency Extract the f...
fastapi [QUESTION] How to send 204 response?
Instead of returning None and instead of injecting the response just return a newly created response...
strapi Refresh JWT route
This is quite important for my app So I implement it by extending plugin (for temporary use) Here's ...
type graphql Cannot determine GraphQL input type for
For future readers This may have been due to using an @ObjectType() CompanyData as an @InputType() i...
amplify cli jest-haste-map: Haste module naming collision: -> namefunction <-
For React Native 0.6x configure the blacklist in metro.config.js instead of rn-cli.config.js as per ...
chi chi@v1.5.x mod issues
I do not want to release /v5 and see it on the import path I'm not sure why you are considering /v5 ...
Jackett The method or operation is not implemented. (all indexers!)
Working on Synology after manual update Note that this worked for my DS415+ that is using the Mono v...
fastapi OpenAPI UI not working properly when using automatic swagger-ui CDN (swagger-ui-3.30.1)
Thanks for reporting it and for all the discussion here everyone! πŸš€ β˜• Indeed it's a bug in Swagger ...
L5 Swagger oauth2 + passport = Bearer <token>
Sharing my solution in case it might help This is I how made it to work with Passport using password...
neovim homebrew build fails to start (segfault in libtermkey 0.21)
EDITOR=/usr/bin/vim brew edit libtermkey edit the URL to libtermkey-0.20.tar.gz and the hash to 6c0d...
core Non anemic doctrine models are not supported
Regarding the general design of API Platform and how it fits with command buses and/or event sourcin...
neovim Feature: optional floating window borders
This works for me Not sure why but it does. #6619 Added floating windows but no way to create a bord...
axios module How to import module to external file
@lukasborawski I think the following solution is far more elegant So let's say that I'm using axios ...
fastapi [QUESTION] Is this the correct way to save an uploaded file ?
@classywhetten FastAPI has almost no custom logic related to UploadFile -- most of it is coming from...
fastapi [QUESTION] Storing object instances in the app context
@ebarlas you're 100% right Description In Flask ...
amplify cli runtime parameter of nodejs8.10 is no longer supported
@asyschikov where can you find the build settings for amplify CLI that you are refering to ? For tho...
graphql engine Support for Mac M1
Hey folks Sorry for the radio silence on the thread from the Hasura team Add Hasura Support for Mac ...
api platform normalization context don't work on symfony v5.1.99
Try to run ./bin/console cache:clear API Platform version(s) affected: x.y.z Description when i make...
amplify cli Connect a cognito user with an AppSync type
Any updates on this? Having to manually write a Lambda triggered by Cognito events to create an AppS...
graphql engine Handling multiple roles on the graphql client (possibly in the same query)
@shahidhk .. my understanding of the current JWT role workflow is: The token is decoded ...