Search code examples
blockchainethereumweb3jstrufflemetamask

Returned values aren't valid, did it run Out of Gas? web3 1.5.0 and sol-0.5.15


I am new to the field of blockchain and ethereum. I have been trying to create a simple testing network using truffle and ganache where I created a new workplace in truffle and tried to build a quick react frontend app to connect to the ethereum using Web3.

Everything works fine. I did install the MetaMask and created a new network to the port:7545 and every change that happened to the ganache affected the MetaMask.

This is the code of web3js.

const web3 = new Web3("http://127.0.0.1:7545")
    const accounts = await web3.eth.getAccounts()
    setaccount(accounts)
    const todoList = new web3.eth.Contract(TodoList.abi, ADRESS);
    console.log('here the todo contract');
    console.log(todoList);
    setTodoList(todoList)
    const taskCount = await todoList.methods.taskCount().call()

The contacts show fine and the account also. but when I tried to call the function, it showed me this error which confused me.

Uncaught (in promise) Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node that is not fully synced.
    at ABICoder.push../node_modules/web3-eth-abi/lib/index.js.ABICoder.decodeParametersWith (index.js:297)
    at ABICoder.push../node_modules/web3-eth-abi/lib/index.js.ABICoder.decodeParameters (index.js:284)
    at Contract.push../node_modules/web3-eth-contract/lib/index.js.Contract._decodeMethodReturn (index.js:469)
    at Method.outputFormatter (index.js:759)
    at Method.push../node_modules/web3-core-method/lib/index.js.Method.formatOutput (index.js:147)
    at sendTxCallback (index.js:523)
    at index.js:307
    at XMLHttpRequest.request.onreadystatechange (index.js:98)
push../node_modules/web3-eth-abi/lib/index.js.ABICoder.decodeParametersWith @ index.js:297
push../node_modules/web3-eth-abi/lib/index.js.ABICoder.decodeParameters @ index.js:284
push../node_modules/web3-eth-contract/lib/index.js.Contract._decodeMethodReturn @ index.js:469
outputFormatter @ index.js:759
push../node_modules/web3-core-method/lib/index.js.Method.formatOutput @ index.js:147
sendTxCallback @ index.js:523
(anonymous) @ index.js:307
request.onreadystatechange @ index.js:98
async function (async)
loadBlockchainDate @ App.js:36
(anonymous) @ App.js:20
invokePassiveEffectCreate @ react-dom.development.js:23487
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
flushPassiveEffectsImpl @ react-dom.development.js:23574
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
flushPassiveEffects @ react-dom.development.js:23447
(anonymous) @ react-dom.development.js:23324
workLoop @ scheduler.development.js:417
flushWork @ scheduler.development.js:390
performWorkUntilDeadline @ scheduler.development.js:157

and this is my solidiy contracts

pragma solidity ^0.5.0;

contract TodoList {
  uint public taskCount = 0;

constructor() public {
     createTask("Check out dappuniversity.com");
   }

  struct Task {
    uint id;
    string content;
    bool completed;
  }

  mapping(uint => Task) public tasks;

  function createTask(string memory _content) public {
    taskCount ++;
    tasks[taskCount] = Task(taskCount, _content, false);
  }

}

and this is the ABI.

[
    {
        "inputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "constructor"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "taskCount",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "name": "tasks",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "id",
                "type": "uint256"
            },
            {
                "internalType": "string",
                "name": "content",
                "type": "string"
            },
            {
                "internalType": "bool",
                "name": "completed",
                "type": "bool"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "internalType": "string",
                "name": "_content",
                "type": "string"
            }
        ],
        "name": "createTask",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    }
]

and this is the contract that I get from web3 when connecting to the abi and address.

Contract
BatchRequest: ƒ ()
clearSubscriptions: ƒ (keepIsSyncing)
currentProvider: (...)
defaultAccount: (...)
defaultBlock: (...)
defaultChain: (...)
defaultCommon: (...)
defaultHardfork: (...)
events: {allEvents: ƒ}
extend: ƒ (extension)
givenProvider: Proxy {_events: {…}, _eventsCount: 1, _maxListeners: 100, _log: a, _state: {…}, …}
handleRevert: (...)
methods:
0x8d977672: ƒ ()
0x111002aa: ƒ ()
0xb6cb58a5: ƒ ()
createTask: ƒ ()
createTask(string): ƒ ()
taskCount: ƒ ()
taskCount(): ƒ ()
tasks: ƒ ()
tasks(uint256): ƒ ()
[[Prototype]]: Object
options: {}
providers: {WebsocketProvider: ƒ, HttpProvider: ƒ, IpcProvider: ƒ}
setProvider: ƒ ()
setRequestManager: manager => {…}
transactionBlockTimeout: (...)
transactionConfirmationBlocks: (...)
transactionPollingTimeout: (...)
_address: "0x8c0199C5D6e4B22A1948358F1bf48dD095Ae5300"
_jsonInterface: (4) [{…}, {…}, {…}, {…}]
_provider: HttpProvider {withCredentials: false, timeout: 0, headers: undefined, agent: undefined, connected: true, …}
_requestManager: RequestManager {provider: HttpProvider, providers: {…}, subscriptions: Map(0)}
get currentProvider: () => { return pkg._provider; }
set currentProvider: value => { return pkg.setProvider(value); }
get defaultAccount: ƒ ()
set defaultAccount: ƒ (val)
get defaultBlock: ƒ ()
set defaultBlock: ƒ (val)
get defaultChain: ƒ ()
set defaultChain: ƒ (val)
get defaultCommon: ƒ ()
set defaultCommon: ƒ (val)
get defaultHardfork: ƒ ()
set defaultHardfork: ƒ (val)
get handleRevert: ƒ ()
set handleRevert: ƒ (val)
get transactionBlockTimeout: ƒ ()
set transactionBlockTimeout: ƒ (val)
get transactionConfirmationBlocks: ƒ ()
set transactionConfirmationBlocks: ƒ (val)
get transactionPollingTimeout: ƒ ()
set transactionPollingTimeout: ƒ (val)
[[Prototype]]: Contract

When I did the truffle version I get this

Truffle v5.4.3 (core: 5.4.3)
Solidity v0.5.16 (solc-js)
Node v14.17.0
Web3.js v1.5.0

and I installed the web3 version 1.5.1 and also tried 1.5.0 but still faced the same error.

this is the tutorial that I am following https://www.dappuniversity.com/articles/ethereum-dapp-react-tutorial

Edit : I am using the Ganache GUI and my Metamask custom sitting is. enter image description here

The Issue : I used the address of the node instead of the address of the contract that after I applied the truffle migrate --reset all .


Solution

  • So I tried the same code using truffle and ganache and it works for me. The only difference is that i am running ganache on port 8545 and connecting metamask with that port in url. I believe that you are providing somewhat incorrect values here const todoList = new web3.eth.Contract(TodoList.abi, ADRESS);

    Make Sure that your contract's abi and address is correct. Read details about instantiation of contract object with correct values here

    Here is how i am reading the JSON file:

    const TodoList = JSON.parse(fs.readFileSync('./build/contracts/TodoList.json', 'utf8'));.

    I am simply extracting the abi from it just like your code. For Contract Address part, I get the address manually from the output console after running truffle migrate --reset all.

    After this you will get a receipt information in console like this

    Replacing 'TodoList'
       --------------------
       > transaction hash:    0x00d16b5ee5f4ddad354543a100d7c730114f5668d5f3b35f1a2306764335c32d
       > Blocks: 0            Seconds: 0
       > contract address:    0x5592F579627C9123F2EB77429B3E6e66891C6a9A
       > block number:        11
       > block timestamp:     1628967561
       > account:             0xa0aC73a479e9B6F5b5Ee0b0Fd241bbb1D83C5ec2
       > balance:             99.95728292
       > gas used:            363127 (0x58a77)
       > gas price:           20 gwei
       > value sent:          0 ETH
       > total cost:          0.00726254 ETH
    

    You need to copy the contract address and put it like this: "0x5592F579627C9123F2EB77429B3E6e66891C6a9A"

    truffle-config.js file: Use this configuration for compiling the contracts

    /**
     * Use this file to configure your truffle project. It's seeded with some
     * common settings for different networks and features like migrations,
     * compilation and testing. Uncomment the ones you need or modify
     * them to suit your project as necessary.
     *
     * More information about configuration can be found at:
     *
     * trufflesuite.com/docs/advanced/configuration
     *
     * To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider)
     * to sign your transactions before they're sent to a remote public node. Infura accounts
     * are available for free at: infura.io/register.
     *
     * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
     * public/private key pairs. If you're publishing your code to GitHub make sure you load this
     * phrase from a file you've .gitignored so it doesn't accidentally become public.
     *
     */
    
    // const HDWalletProvider = require('@truffle/hdwallet-provider');
    //
    // const fs = require('fs');
    // const mnemonic = fs.readFileSync(".secret").toString().trim();
    
    module.exports = {
      /**
       * Networks define how you connect to your ethereum client and let you set the
       * defaults web3 uses to send transactions. If you don't specify one truffle
       * will spin up a development blockchain for you on port 9545 when you
       * run `develop` or `test`. You can ask a truffle command to use a specific
       * network from the command line, e.g
       *
       * $ truffle test --network <network-name>
       */
    
      networks: {
        // Useful for testing. The `development` name is special - truffle uses it by default
        // if it's defined here and no other network is specified at the command line.
        // You should run a client (like ganache-cli, geth or parity) in a separate terminal
        // tab if you use this network and you must also set the `host`, `port` and `network_id`
        // options below to some value.
        //
        development: {
         host: "127.0.0.1",     // Localhost (default: none)
         port: 7545,            // Standard Ethereum port (default: none)
         network_id: "*"       // Any network (default: none)
        },
        // Another network with more advanced options...
        // advanced: {
        // port: 8777,             // Custom port
        // network_id: 1342,       // Custom network
        // gas: 6000000,           // Gas sent with each transaction (default: ~6700000)
        // gasPrice: 20000000000,  // 20 gwei (in wei) (default: 100 gwei)
        // from: <address>,        // Account to send txs from (default: accounts[0])
        // websocket: true        // Enable EventEmitter interface for web3 (default: false)
        // },
        // Useful for deploying to a public network.
        // NB: It's important to wrap the provider as a function.
        // ropsten: {
        // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
        // network_id: 3,       // Ropsten's id
        // gas: 5500000,        // Ropsten has a lower block limit than mainnet
        // confirmations: 2,    // # of confs to wait between deployments. (default: 0)
        // timeoutBlocks: 200,  // # of blocks before a deployment times out  (minimum/default: 50)
        // skipDryRun: true     // Skip dry run before migrations? (default: false for public nets )
        // },
        // Useful for private networks
        // private: {
        // provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
        // network_id: 2111,   // This network is yours, in the cloud.
        // production: true    // Treats this network as if it was a public net. (default: false)
        // }
      },
    
      // Set default mocha options here, use special reporters etc.
      mocha: {
        // timeout: 100000
      },
    
      // Configure your compilers
      compilers: {
        solc: {
          version: "0.5.0",    // Fetch exact version from solc-bin (default: truffle's version)
          docker: false,        // Use "0.5.1" you've installed locally with docker (default: false)
          settings: {          // See the solidity docs for advice about optimization and evmVersion
           optimizer: {
             enabled: false,
             runs: 200
           },
           evmVersion: "byzantium"
          }
        }
      },
    
      // Truffle DB is currently disabled by default; to enable it, change enabled: false to enabled: true
      //
      // Note: if you migrated your contracts prior to enabling this field in your Truffle project and want
      // those previously migrated contracts available in the .db directory, you will need to run the following:
      // $ truffle migrate --reset --compile-all
    
      db: {
        enabled: false
      }
    };