web3.js Error: Couldn't decode uint8 from ABI: 0x - web3js

env: mac node web3
I am trying to use a smart contract instance for a deployed contract in node.js. I am getting the error below and don't know how to solve it.
code:
app.js
web3.eth.getBlock(0, function (error, result) {
if (!error) {
web3.eth.personal.newAccount("test", function (error, result) {
if (!error) {
console.log("new account:", result);
//init contract
var smartToken = new web3.eth.Contract(config.smartTokenAbi, config.smartTokenAddr, {
from: result,
gasPrice: '20000000000'
});
var privateSale = new web3.eth.Contract(config.privateSaleAbi, config.privateSaleAddr, {
from: result,
gasPrice: '20000000000'
});
privateSale.methods.state().call({}, function (error, result) {
console.log("------", error, result);
});
} else {
console.log(error)
}
});
console.log("Connect to " + config.host + ' success');
} else {
console.log("Can't connect to " + config.host);
throw error;
}
});
output:
new account: 0x7051ebDe6A252858A3E5b06Dc7608677B18EC093
------ Error: Couldn't decode uint8 from ABI: 0x
at SolidityTypeUInt.formatOutputUInt [as _outputFormatter] (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-abi#1.0.0-beta.34#web3-eth-abi/src/formatters.js:174:15)
at SolidityTypeUInt.SolidityType.decode (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-abi#1.0.0-beta.34#web3-eth-abi/src/type.js:252:17)
at /Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-abi#1.0.0-beta.34#web3-eth-abi/src/index.js:327:49
at Array.forEach (<anonymous>)
at ABICoder.decodeParameters (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-abi#1.0.0-beta.34#web3-eth-abi/src/index.js:326:13)
at Contract._decodeMethodReturn (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-contract#1.0.0-beta.34#web3-eth-contract/src/index.js:459:22)
at Method.outputFormatter (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-eth-contract#1.0.0-beta.34#web3-eth-contract/src/index.js:812:46)
at Method.formatOutput (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-core-method#1.0.0-beta.34#web3-core-method/src/index.js:163:54)
at sendTxCallback (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-core-method#1.0.0-beta.34#web3-core-method/src/index.js:475:33)
at /Volumes/Seagate/cqyh/ABC/node_modules/_web3-core-requestmanager#1.0.0-beta.34#web3-core-requestmanager/src/index.js:147:9
at XMLHttpRequest.request.onreadystatechange (/Volumes/Seagate/cqyh/ABC/node_modules/_web3-providers-http#1.0.0-beta.34#web3-providers-http/src/index.js:77:13)
at XMLHttpRequestEventTarget.dispatchEvent (/Volumes/Seagate/cqyh/ABC/node_modules/_xhr2#0.1.4#xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/Volumes/Seagate/cqyh/ABC/node_modules/_xhr2#0.1.4#xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/Volumes/Seagate/cqyh/ABC/node_modules/_xhr2#0.1.4#xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/Volumes/Seagate/cqyh/ABC/node_modules/_xhr2#0.1.4#xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9) undefined

Related

Cannot update or save data on second or next user in mongodb

May I know what is the problem with my code for the backend. I try to create a place and update it in the user database. The problem is If I only have 1 user. The database can create and update the data but if I have more than 2 then, the data cannot be updated or created. Here is my code. I have been working on this part for so long, that I cannot find the solution.
const createFile = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
}
const { userId, Dataset } = req.body;
const createdFile = new File({
userId,
Dataset,
});
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again 1',
500
);
return next(error);
}
if (!user) {
const error = new HttpError('Could not find user for provided id', 404);
return next(error);
}
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await createdFile.save({ session: sess });
user.Dataset.push(createdFile);
await user.save({ session: sess });
await sess.commitTransaction();
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again.2',
500
);
return next(error);
}
res.status(201).json({ files: createdFile });
};
The error message that I got
Error: User validation failed: _id: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at ValidationError.inspect (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\error\validation.js:48:26)
at internal/per_context/primordials.js:23:32
at formatValue (internal/util/inspect.js:783:19)
at inspect (internal/util/inspect.js:337:10)
at formatWithOptionsInternal (internal/util/inspect.js:2016:40)
at formatWithOptions (internal/util/inspect.js:1898:10)
at console.value (internal/console/constructor.js:323:14)
at console.log (internal/console/constructor.js:358:61)
at createFile (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\controllers\files-controller.js:102:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errors: {
_id: ValidatorError: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at validate (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1321:13)
at C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1297:24
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
properties: [Object],
kind: 'unique',
path: '_id',
value: new ObjectId("62c661c629d1cb99768efd05"),
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
It already settle, I reroll the mongoose-unique-validator to 2.0.3 version
I use this command
npm install mongoose-unique-validator#2.0.3 --legacy-peer-deps
hope that someone with same issues as mine find my post and can help them to solve the same issues

Getting "Error Authenticator must be set" when call AuthorizationV1 to obtain speech-to-text token

Running Node v10
ibm-watson v5.1.0
Getting error when try to obtain token for speech-to-text.
#
{
"message": "Authenticator must be set.",
"name": "Error",
"stack": "Error: Authenticator must be set.\n at AuthorizationV1.BaseService (/nodejsAction/VuncPM95/node_modules/ibm-cloud-sdk-core/lib/base-service.js:66:19)\n at new AuthorizationV1 (/nodejsAction/VuncPM95/node_modules/ibm-watson/authorization/v1.js:44:28)\n at Object.token (/nodejsAction/VuncPM95/services/stt.js:17:32)\n at speech-to-text_token (/nodejsAction/VuncPM95/index.js:42:54)\n at Object.exec (/nodejsAction/VuncPM95/index.js:33:73)\n at Promise (/nodejsAction/VuncPM95/index.js:10:16)\n at new Promise ()\n at NodeActionRunner.main [as userScriptMain] (/nodejsAction/VuncPM95/index.js:9:12)\n at Promise (/nodejsAction/runner.js:73:35)\n at new Promise ()"
}
#
When try with
typescript 3.6.4
#
{
"message": "Authenticator must be set.",
"name": "Error",
"stack": "Error: Authenticator must be set.\n at t.e (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:45665)\n at new t (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :16:49145)\n at Object.token (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:44594)\n at speech-to-text_token (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:43617)\n at Object.exec (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:43498)\n at Promise (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:43038)\n at new Promise ()\n at NodeActionRunner.a [as userScriptMain] (eval at initializeActionHandler (/nodejsAction/runner.js:57:23), :22:43016)\n at Promise (/nodejsAction/runner.js:73:35)\n at new Promise ()"
}
#
export const SpeechToText = {
token: (params: WatsonParams) => {
const sttCredentials = Object.assign(
{
username: params.speechToTextUsername, // or hard-code credentials here
password: params.speechToTextPassword,
iam_apikey: params.speechToTextIamApikey, // if using an RC service
url: params.speechToTextUrl ? params.speechToTextUrl : SpeechToTextV1.URL
},
vcapServices.getCredentials('speech_to_text') // pulls credentials from environment in bluemix, otherwise returns {}
);
const sttAuthService = new AuthorizationV1(sttCredentials);
return Observable.create((observer) => {
sttAuthService.getToken(function(err, response) {
if (err) {
console.log('Error retrieving token: ', err);
observer.error('Error retrieving token...');
} else {
const token = response.token || response;
if (params.speechToTextIamApikey) {
observer.next({ accessToken: token, url: sttCredentials.url });
} else {
observer.next({ token: token, url: sttCredentials.url });
}
observer.complete();
}
});
});
}
}
Expect it to return a token.
Authentication changed in v5. See MIGRATION-V5
The SDK service constructors now accept Authenticator objects that are used to authenticate requests. The constructors no longer accept individual credentials like username and password.
Here's an example from the API reference.
const SpeechToTextV1 = require('ibm-watson/speech-to-text/v1');
const { IamAuthenticator } = require('ibm-watson/auth');
const speechToText = new SpeechToTextV1({
authenticator: new IamAuthenticator({
apikey: '{apikey}',
}),
url: '{url}',
});

Meteor call inside cursor.map throws error

I have a meteor call "Send to all" inside another meteor call and cursor.map which throws error on server side but runs fine on client side below is the error: how do i remove this error ? meteor 1.8 react 16.8
send all numbers error2 { Error: Method 'Send to all' not found [404]
I20190720-13:08:56.527(5.5)? at Server.applyAsync (packages/ddp-server/livedata_server.js:1648:9)
I20190720-13:08:56.528(5.5)? at Server.apply (packages/ddp-server/livedata_server.js:1625:26)
I20190720-13:08:56.529(5.5)? at Server.call (packages/ddp-server/livedata_server.js:1607:17)
I20190720-13:08:56.530(5.5)? at Find all numbers.userKisandb.find.fetch.map.Mob (imports/api/userKisan.js:47:24)
I20190720-13:08:56.531(5.5)? at Array.map (<anonymous>)
I20190720-13:08:56.531(5.5)? at MethodInvocation.Find all numbers (imports/api/userKisan.js:44:21)
I20190720-13:08:56.532(5.5)? at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1771:12)
I20190720-13:08:56.533(5.5)? at DDP._CurrentMethodInvocation.withValue (packages/ddp-server/livedata_server.js:719:19)
I20190720-13:08:56.533(5.5)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1234:12)
I20190720-13:08:56.534(5.5)? at DDPServer._CurrentWriteFence.withValue (packages/ddp-server/livedata_server.js:717:46)
I20190720-13:08:56.536(5.5)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1234:12)
I20190720-13:08:56.537(5.5)? at Promise (packages/ddp-server/livedata_server.js:715:46)
I20190720-13:08:56.539(5.5)? at new Promise (<anonymous>)
I20190720-13:08:56.539(5.5)? at Session.method (packages/ddp-server/livedata_server.js:689:23)
I20190720-13:08:56.540(5.5)? at packages/ddp-server/livedata_server.js:559:43
I20190720-13:08:56.541(5.5)? isClientSafe: true,
I20190720-13:08:56.542(5.5)? error: 404,
I20190720-13:08:56.542(5.5)? reason: 'Method \'Send to all\' not found',
I20190720-13:08:56.544(5.5)? details: undefined,
I20190720-13:08:56.544(5.5)? message: 'Method \'Send to all\' not found [404]',
I20190720-13:08:56.545(5.5)? errorType: 'Meteor.Error' }
'Find all numbers' (smsText) {
if(!this.userId) {
throw new Meteor.Error('not-authorized');
}
return userKisandb.find({
userId: this.userId
}).fetch().map((Mob) => {
// return Mob.Mnumber
if(Mob.Mnumber) {
Meteor.call('Send to all',Mob.Mnumber,smsText,(err,resp) => {
//this call throws error on server side
//sms.js
if(err){
console.log("send all numbers error2", err);
} else {
console.log("send all numbers sucess", resp);
}
})
}
});
},
And Method is
Meteor.methods({
'Send to all'(mob,text) {
let from = 1234;
console.log(from);
},
})

throw new ERR_INVALID_ARG_TYPE('chunk',['string','Buffer'],chunk);TypeError[ERR_INVALID_ARG_TYPE]:The "chunk" arg must be type string or Buffer

I am trying to get the contents of a .json file using a node js service into an angularjs method. But am getting following error:
_http_outgoing.js:700
throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
at ServerResponse.end (_http_outgoing.js:700:13)
here are the corresponding code fragments...
angular controller: the commented lines are all of those which i have tried and failed with.
var currentProcess = "process_1cA";
$scope.storestats = [];
var resAss = $resource('/procs/getstorestats');
var stats = resAss.get({
process: currentProcess,
date: date.getFullYear() + "" + m + "" + d
});
stats.$promise.then(function(response) {
if (response != undefined) {
// var r = JSON.parse(response);
//$scope.storestats.push(r);
//$scope.storestats.push(r);
//var r = JSON.parse(response);
$scope.storestats.push(response);
//angular.forEach(r, function(value, key) {
// $scope.storestats.push({key : value});
//});
}
});
NODEJs service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.end(msgs1);
});
}
catch (err) {
res.end(err.toString());
}});
P.S: The commented out lines are those which i have tried out with and failed. Also, the commented lines in the node service code snippet, give no error, and when logged show it correctly, but the data when in response of the controllers is blank.
I'm guessing a bit here, but I think you just need to change res.end() to res.send() in your Node code. The "end" method is used when you are streaming chunks of data and then you call end() when you're all done. The "send" method is for sending a response in one go and letting Node handle the streaming.
Also, be sure you are sending a string back!
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.send(msgs2); // NOTE THE CHANGE to `msg2` (the string version)
});
}
catch (err) {
res.send(err.toString()); // NOTE THE CHANGE
}
});
I had a similar error. It was because I was passing process.pid to res.end(). It worked when I changed process.pid to string
res.end(process.pid.toString());
Figured it out. 2 small changes were needed.. One in the controller, which was to use a "$resource.query" instead of "$resource.get". And in the service, as #jakarella said, had to use the stringified part in the .end();
Controller:
var resAss = $resource('/procs/getstorestats');
var stats = resAss.query({process: currentProcess, date: date.getFullYear() + "" + m + "" + d});
stats.$promise.then(function (response) {
$scope.storestats.push(response);
}
Node Service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
var msgs2 = JSON.stringify(msgs1);
console.log(msgs2);
res.end(msgs2);
});
}
If you are using 'request-promise' library set the json
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
})
.catch(function (err) {
});
Thank you user6184932, it work
try {
await insertNewDocument(fileNameDB, taskId);
res.end(process.pid.toString());
} catch (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
in mysql2 the reason for the error is the sql word , sql is a query :
const sql = select * from tableName
pool.executeQuery({
sql,
name: 'Error list for given SRC ID',
values: [],
errorMsg: 'Error occurred on fetching '
})
.then(data => {
res.status(200).json({ data })
})
.catch(err => {
console.log('\n \n == db , icorp fetching erro ====> : ', err.message, '\n \n')
})
I got the error using Node v12 (12.14.1).
Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number
Sample code for context.
const { Readable } = require('stream')
Readable.from(Buffer.from(base64content, 'base64'))
.pipe( ... )
Solution (for my case), was upgrading to Node v14 (14.17.3). e.g.
nvm use 14
nvm

Uncaught TypeError: __webpack_require__(...).connect is not a function at connect (index.js:47532) at Object.connect (

I am getting this error
when I am trying to test code on react project:
var amqp = require('amqplib/callback_api');
export function start2 (conn) {
console.log("hello")
amqp.connect('amqp://localhost:8000', function (err, conn) {
conn.createChannel(function(err, ch) {
var q = 'frontend';
var msg = 'Hello!';
ch.assertQueue(q, {durable: false});
// Note: on Node 6 Buffer.from(msg) should be used
ch.sendToQueue(q, new Buffer(msg));
console.log(" [x] Sent %s", msg);
});
setTimeout(function() { conn.close(); process.exit(0) }, 500);
});
}
any help please and thanks.

Resources