0

Here is my contract

https://kovan.etherscan.io/address/0x9c08fb4e6666a796ef1ade3f58cb0a3e3f469e7c#code

I was trying to call the function in the contract by web3 ,for example:

//address and abi are copied from url above
let contractAddr = contract.address 
let contractAbi = contract.abi
let web3 = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws'))
if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider)
} else {
  console.log('we need MetaMask')
}

let myContract = new web3.eth.Contract(contractAbi, contractAddr)
myContract.methods.name().call().then(console.log).catch(console.log)

I got this:

Error: ERROR: The returned value is not a convertible string:

However, if I copy the contract to

https://remix.ethereum.org/#optimize=true&version=soljson-v0.4.24+commit.e67f0147.js

and I use Ganache. Then my code would be:

//address and abi are copied from url above
let contractAddr = contract.address
let contractAbi = contract.abi
let url = contract.url //http://127.0.0.1:7545 provided by ganache
let web3
if (typeof web3 !== 'undefined') {
  // web3 = new Web3(web3.currentProvider)
} else {
  web3 = new Web3(new Web3.providers.HttpProvider(url))
}
let myContract = new web3.eth.Contract(contractAbi, contractAddr)
myContract.methods.name().call().then(console.log).catch(console.log)

In this case, I will get the right result 'MOMO'.

I would think Infura works like Ganache and I have tried other Infura URLs, but all failed.

I have MetaMask in my chrome extension and use we web3@^1.0.0-beta.33.

How can I call the function in

https://kovan.etherscan.io/address/0x9c08fb4e6666a796ef1ade3f58cb0a3e3f469e7c#code

just like I call it in

https://remix.ethereum.org/#optimize=true&version=soljson-v0.4.24+commit.e67f0147.js

by ganache.

TylerH
  • 20,799
  • 66
  • 75
  • 101
xianshenglu
  • 4,943
  • 3
  • 17
  • 34

1 Answers1

1

It looks like you're connected to mainnet instead of kovan:

let web3 = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws'))

That should read:

let web3 = new Web3(new Web3.providers.WebsocketProvider('wss://kovan.infura.io/ws'))
user94559
  • 59,196
  • 6
  • 103
  • 103
  • Oh, sorry, I just saw that this is only a fallback if MetaMask isn't detected. It should still be updated, but if you do have MetaMask running, then you should instead be double checking that _MetaMask_ is connected to Kovan. – user94559 Aug 28 '18 at 17:25
  • That is the point! In the beginning I find these `[ 'wss://mainnet.infura.io/ws', 'wss://ropsten.infura.io/ws', 'wss://rinkeby.infura.io/ws' ]`. They all can't work. Until I see your answer and other articles , I realized maybe the name is the key. – xianshenglu Sep 02 '18 at 06:59