Sending signTransaction with web3.js and getting the issues - node.js

Blockchain, web3.js issue
----------------
I am new on block-chain and try to make transactions using ropsten test network but getting errors
Thanks in advance if anyone can help me.
exports.sendTransactions = () => {
var admin = "0xEF9dE245F335e0f3ae8A9563FD54D001de1d3E2D";
var contract_address = "0x39E2f0E87027093C6Ffe76A4d2f20AEE479E5f64";
var tx = {
from: admin,
to: contract_address,
gas: 184000,
data: "",`enter code here`
chainId: "1337"
};
web3.eth.accounts.signTransaction(tx, 'privateKey').then((hash) => {
web3.eth.sendSignedTransaction(hash.rawTransaction).then((receipt) => {
resolve();
}, (error) => {
console.log(error);
reject(500);
});
}, (error) => {
reject(500);
});
}
{ messageHash: '0x15e3f440015b35151c1343fb9a6be2497c082b47dbce607d32e80c10eff800f1',
v: '0xa95',
r: '0x4446233885e382fc9f297dc47fe9294be57623341b781eece94ce28b52bec6ed',
s: '0x51b096eb07f73d5a30757300caf990b4083d001d2f6aea0fca280aafbea5593d',
rawTransaction: '0xf8678085012a05f2008302cec09439e2f0e87027093c6ffe76a4d2f20aee479e5f648080820a95a04446233885e382fc9f297dc47fe9294be57623341b781eece94ce28b52bec6eda051b096eb07f73d5a30757300caf990b4083d001d2f6aea0fca280aafbea5593d' }
Error: Returned error: invalid sender
at Object.ErrorResponse (/home/ri-8/Desktop/tokenAI/node_modules/web3-core-helpers/src/errors.js:29:16)
at /home/ri-8/Desktop/tokenAI/node_modules/web3-core-requestmanager/src/index.js:137:36
at XMLHttpRequest.request.onreadystatechange (/home/ri-8/Desktop/tokenAI/node_modules/web3-providers-http/src/index.js:77:13)
at XMLHttpRequestEventTarget.dispatchEvent (/home/ri-8/Desktop/tokenAI/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/home/ri-8/Desktop/tokenAI/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/home/ri-8/Desktop/tokenAI/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/home/ri-8/Desktop/tokenAI/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:110:20)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1059:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)

The chain ID for Ropsten is 3 (see EIP 155), but you've supplied 1337.

Related

Dropbox API integration on AWS Lambda gets FetchError (ETIMEDOUT)

I have a node.js app which runs on AWS Lambda. The Lambda is connected with a VPC. It goes internet with a static IP. I use v10.23.0 dropbox-sdk-js. It always seems to run on my local but it sometimes runs on the lambda, sometimes gets fetch error.
My code is like this:
async function main() {
const Dropbox = require('dropbox').Dropbox;
const dropbox = {
dbx: new Dropbox({
accessToken: process.env.ACCESS_TOKEN,
pathRoot: JSON.stringify({ '.tag': 'namespace_id', 'namespace_id': process.env.NAMESPACE_ID })
})
};
const payload = {
path: '',
recursive: true,
include_media_info: false,
include_deleted: false,
include_has_explicit_shared_members: true,
include_mounted_folders: true,
include_non_downloadable_files: true
};
let hasMore = true;
let entries = [];
let response;
let cursor;
while (hasMore) {
try {
if (cursor) {
response = await dropbox.dbx.filesListFolderContinue({ cursor: cursor });
}
else {
response = await dropbox.dbx.filesListFolderGetLatestCursor(payload);
response = await dropbox.dbx.filesListFolderContinue({ cursor: response.result.cursor });
}
console.info('Entries: ', JSON.stringify(response.result.entries));
cursor = response.result.cursor;
entries = entries.concat(response.result.entries);
hasMore = response.result.has_more;
}
catch (error) {
console.info(error);
return error;
}
}
}
main();
Error log:
2022-01-20T08:22:18.579Z 67caa239-e75c-46ce-be4c-0fcf6c154694 INFO FetchError: request to https://api.dropboxapi.com/2/files/list_folder/continue failed, reason: connect ETIMEDOUT 162.125.4.19:443
at ClientRequest.<anonymous> (/var/task/node_modules/dropbox/node_modules/node-fetch/lib/index.js:1483:11)
at ClientRequest.emit (events.js:400:28)
at TLSSocket.socketErrorListener (_http_client.js:475:9)
at TLSSocket.emit (events.js:400:28)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
type: 'system',
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT'
}
I deattached VPC from lambda and it worked. I think AWS blocks fetching while you are using VPC.

Node.JS aws-sdk getting "socket hang up" error

I am trying to get the pricing information of AmazonEC2 machines using "#aws-sdk/client-pricing-node" package.
Each time I will send a request to get the pricing information, process it, and send the request again, until all the information is obtained (no NextToken anymore). The following is my code.
const {
PricingClient,
} = require('#aws-sdk/client-pricing-node/PricingClient');
const {
GetProductsCommand,
} = require('#aws-sdk/client-pricing-node/commands/GetProductsCommand');
const agent = new https.Agent({
maxSockets: 30,
keepAlive: true,
});
const pricing = new PricingClient({
region: "us-east-1",
httpOptions: {
timeout: 45000,
connectTimeout: 45000,
agent,
},
maxRetries: 10,
retryDelayOptions: {
base: 500,
},
});
const getProductsCommand = new GetProductsCommand( { ServiceCode: 'AmazonEC2', });
async function sendRequest() {
let result = false;
while (!result) {
try {
const data = await pricing.send(getProductsCommand);
result = await handleReqResults(data);
} catch (error) {
console.error(error);
}
}
}
async function handleReqResults(data) {
// some data handling code here
// ...
//return false when there is "NextToken" in the response data
if (data.NextToken) {
setNextToken(data.NextToken);
return false;
}
return true;
}
The code will run for a while (variable time) and then stop with the following error:
{ Error: socket hang up
at createHangUpError (_http_client.js:332:15)
at TLSSocket.socketOnEnd (_http_client.js:435:23)
at TLSSocket.emit (events.js:203:15)
at TLSSocket.EventEmitter.emit (domain.js:448:20)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
code: 'ECONNRESET',
'$metadata': { retries: 0, totalRetryDelay: 0 } }
I had tried to run it on a GCP VM instance, and there was no such a problem. But the problem happens when I run it on my local machine.
Do anyone have any idea how to solve this problem?
(BTW: my node version is v10.20.1)

Howo to get IPP endpoint

I'm using the ipp npm module to send a print job from a google cloud function. I believe I have set up the printer correctly but I don't know how I'm supposed to know the exact uri for sending the print job.
The printer model is Brother MFC-L3770CDW
Here is how my settings look in the web view for the printer configuration.
And here is the function code.:
var ipp = require('ipp');
var PDFDocument = require('pdfkit');
var doc = new PDFDocument;
doc.text("Hello World");
var buffers = [];
doc.on('data', buffers.push.bind(buffers));
doc.on('end', function () {
var printer = ipp.Printer("https://10.0.0.55:443");
var file = {
"operation-attributes-tag":{
"requesting-user-name": "User",
"job-name": "Print Job",
"document-format": "application/pdf"
},
data: Buffer.concat(buffers)
};
printer.execute("Print-Job", file, function (err, res) {
if(err) {
console.log(err);
}
else{
console.log("Printed: "+res.statusCode);
}
});
console.log('executing');
});
doc.end();
console.log('finished executing');
I have tried various uris such as
https://10.0.0.55:631
https://10.0.0.55:443
https://10.0.0.55:631/ipp
https://10.0.0.55:631/ipp/printer
Sometimes I get an error like:
"Error: socket hang up
at TLSSocket.onHangUp (_tls_wrap.js:1148:19)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at TLSSocket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
at _combinedTickCallback (internal/process/next_tick.js:139:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
code: 'ECONNRESET',
path: null,
host: '10.0.0.55',
port: '631',
localAddress: undefined }"

If I disable NODE_TLS_REJECT_UNAUTHORIZED, my request is still denied

I am disabling Node from rejecting self signed certificates and making a request.
const { USER, PW } = process.env;
const b64 = new Buffer(`${VP_API_USER}:${VP_API_PW}`).toString("base64");
const Authorization = `Basic ${b64}`;
const doFind = async url => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const results = await fetch(url, { headers: { Authorization } })
.then(r => (r.ok ? r.json() : Promise.reject(r)))
.catch(err => {
return Promise.reject(err);
});
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
return results;
};
I am still being rejected.
{ FetchError: request to https://<url>:55544/contracts failed, reason: connect ECONNREFUSED <url>:55544
at ClientRequest.<anonymous> (/Users/mjhamm75/Developer/sedd-monorepo/node_modules/node-fetch/index.js:133:11)
at emitOne (events.js:116:13)
at ClientRequest.emit (events.js:211:7)
at TLSSocket.socketErrorListener (_http_client.js:387:9)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
name: 'FetchError',
message: 'request to https://<url>:55544/contracts failed, reason: connect ECONNREFUSED <url>:55544',
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED' }
What am I doing wrong?
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
line should go inside the callback (your then or catch before the return. because a promise gets resolved in the callback, but your line
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
is written outside of it, even though it appears after the statement, it runs immediately without waiting for the callback. so, your tls is effectively never disabled.
I hope this helps:)
Previous answer looks incorrect - await postpones execution of next line until promise will be resolved.
According to the documentation the NODE_TLS_REJECT_UNAUTHORIZED value should be string '0' to disable TLS validation.
This is how I would approach it, if I had to reset the env var afterwards.
Using .finally() the statement will execute regardless of the outcome of the fetch.
const doFind = async url => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
const results = await fetch(url, { headers: { Authorization } })
.then(r => (r.ok ? r.json() : Promise.reject(r)))
.catch(err => {
return Promise.reject(err);
})
.finally(() => {
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 1;
});
return results;
};

How to search via elasticsearch in Node.js?

I have indexed data from firebase via elasticSearch .
And Its Working Properly .
Now I am Searching data via firebase below cloud function :
exports.searchIt = functions.database.ref('/search/{key}')
.onUpdate(event => {
let key=event.params.key;
let elasticSearchConfig = functions.config().elasticsearch;
const esClient = new elastic.Client({
host: 'http://35.198.221.164',
log: 'error'
});
console.log('client Created');
let searchBody = {
size: 20,
from: 0,
query: {
match_all: {}
}
};
esClient.search({index: 'offers', body: searchBody})
.then(results => {
console.log('Successfully Entered');
results.hits.hits.forEach(
(hit, index) => console.log(hit)
)
})
.catch(console.error);
});
But this gives error below :
textPayload: "{ Error: Not Found at respond
(/user_code/node_modules/elasticsearch/src/lib/transport.js:307:15) at
checkRespForFailure
(/user_code/node_modules/elasticsearch/src/lib/transport.js:266:7) at
HttpConnector.
(/user_code/node_modules/elasticsearch/src/lib/connectors/http.js:159:7)
at IncomingMessage.bound
(/user_code/node_modules/elasticsearch/node_modules/lodash/dist/lodash.js:729:21)
at emitNone (events.js:91:20) at IncomingMessage.emit
(events.js:185:7) at endReadableNT (_stream_readable.js:974:12) at
_combinedTickCallback (internal/process/next_tick.js:80:11) at process._tickDomainCallback (internal/process/next_tick.js:128:9)
And on changing host to any other it still create client.
Why is this happening?

Resources