Go-Ethereum – Resolving ‘Invalid Argument 0: json: cannot unmarshal object into Go value of type string’ Error

go-ethereumshhweb3js

I have followed following solution.

When I try to do shh.getPrivateKey(kId).then(console.log)

I have received following error, please note that this line works under web3.py:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Returned error: invalid argument 0: json: cannot unmarshal object into Go value of type string

[Q] How could I fix this error?


web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));    
if(!web3.isConnected()){console.log("notconnected"); process.exit();}

var Shh = require('web3-shh');
// "Shh.providers.givenProvider" will be set if in an Ethereum supported browser.
var shh = new Shh(Shh.givenProvider || 'http://localhost:8545');

var kId = shh.newKeyPair().then(console.log); //b9180e43e5b712868482173d71cf18ff78900e645699d00f9129d6458aaa1fb7
var privateKey = shh.getPrivateKey(kId); //Error Occurs!!!

Best Answer

You need to use callbacks so that the asynchronous functions return a value when it has finished processing. Or use async / await.

The line var privateKey = shh.getPrivateKey(kId); will get executed before kId has a value, because the newKeyPair function has not completed yet.

Most web3.js objects allow a callback as the last parameter, as well as returning promises to chain functions.

https://web3js.readthedocs.io/en/1.0/callbacks-promises-events.html

Callbacks documentation, examples: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

So using async / await instead of callbacks, you can try something like:

Web3 = require("web3");
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));     

async function connect() { //note async function declaration
    if(!await web3.isConnected()){ //await web3@0.20.5
    //if(!await web3.eth.net.isListening()){ //await web3@1.0.0-beta.34
        console.log("notconnected");
        process.exit();
    }

    var kId = await web3.shh.newKeyPair(); 
    var privateKey = await web3.shh.getPrivateKey(kId); //the await keyword resolves the promise

    console.log(privateKey);

}

connect();