Error: argumento no válido 0: json: no se puede desarmar el objeto en el valor Go de tipo cadena

He seguido la siguiente solución .

Cuando trato de hacershh.getPrivateKey(kId).then(console.log)

Recibí el siguiente error, tenga en cuenta que esta línea funciona bajo 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

[P] ¿Cómo podría solucionar este 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!!!

Respuestas (1)

Debe usar devoluciones de llamada para que las funciones asincrónicas devuelvan un valor cuando haya terminado de procesarse. O use async/await.

La línea var privateKey = shh.getPrivateKey(kId);se ejecutará antes de que kId tenga un valor, porque la función newKeyPair aún no se ha completado.

La mayoría de los objetos web3.js permiten una devolución de llamada como último parámetro, además de devolver promesas a funciones de cadena.

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

Documentación de devoluciones de llamadas, ejemplos: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Entonces, al usar async / await en lugar de devoluciones de llamada, puede intentar algo como:

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