Search code examples
javascriptethereumsolidityweb3js

How to fix an 'Uncaught Error: invalid address' error?


I deployed my contract to Goerli test net. Deploying was successful. And I tested it in Remix.

Contract code:

pragma solidity ^0.5.0;

contract Test{
    
    string private str;
    
    constructor() public {
        str = " ";
    }
    
    function getStr() public view returns(string memory  _str){
        _str = str;
    }
    
    function setStr(string memory  _str) public{
        str = _str;
    }
}

Then I tried to make a web interface using web3 and MetaMask.

<script>
        ethereum.enable()
        var abi = [
    {
        "constant": false,
        "inputs": [
            {
                "internalType": "string",
                "name": "_str",
                "type": "string"
            }
        ],
        "name": "setStr",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "constructor"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "getStr",
        "outputs": [
            {
                "internalType": "string",
                "name": "_str",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    }
    ];
        var address = 0x4316d047388e61EBC3Ed34DFf4cEE215840decDa;
        var myContract = web3.eth.contract(abi);
        var TestC = myContract.at(address);
        console.log(TestC);
    var x = TestC.getStr();
</script>

And when I ran it, it returned:

Uncaught Error: invalid address

at c (inpage.js:1)

at inputCallFormatter (inpage.js:1)

at inpage.js:1

at Array.map ()

at o.formatInput (inpage.js:1)

at o.toPayload (inpage.js:1)

at w.e [as call] (inpage.js:1)

at u.call (inpage.js:1)

at u.execute (inpage.js:1)

at (index):46

What I need to do?


Solution

  • Your variable address should be a hex string, not a literal hex number - even though it is eventually turned into a number by the ethereum node.

    Try this instead:

    var address = '0x4316d047388e61EBC3Ed34DFf4cEE215840decDa';