I'm trying to interact with a BSC Smartcontract using Ethersjs and here is my code:
require("dotenv").config();
const { ethers } = require("ethers");
const pk = process.env.PRIVATE_KEY;
const bsc_jsonRPC_testnet = "https://data-seed-prebsc-1-s1.binance.org:8545/" // json RPC url
const provider = new ethers.providers.JsonRpcProvider(bsc_jsonRPC_testnet);
let wallet = new ethers.Wallet(pk, provider);
const CONTRACT_ABI = require('./abis/vino.json'); // set ABI
const CONTRACT_ADDRESS = '0x21f59c8D31EF2E3E472793b28CAc4553aac7a72a';
let contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, provider);
var numberOfDecimals = 18;
const activeProvider = contract.provider.connection.url;
const methods = contract.functions
console.log(methods.name().then((res) => {
console.log(res)
}).catch((e) => {
console.log(e)
}));
console.log('URL PROVIDER: ', activeProvider);
And here what I'm getting from console:
I tried changing chains and providers but no success.
Related
i need to cache a query with redis and node js , the database is aws s3 ,the problem here as a noob ,i will recive the query as a string, i need to encode the keys in the body request so when i will later try to fetsch the data i will use one of those keys(they need to be seperated with '/') can anyone help me with that and bunch of thanks.
here is what i' tried to do:
const { default: axios } = require('axios');
const express = require('express');
const redisClient = require('./helper/Client')
const app = express();
const port = process.env.PORT || 3000
app.use(express.json());
async function fetchApi(species){
const apiResponse = await axios.get(`https://www.fishwatch.gov/api/species/${species}`)
console.log('request sent successfully');
return apiResponse.data
}
async function getSpeciesData(req, res) {
const species = req.body;
const keys = Object.keys(species);
const encodedParams = {};
for (const key of keys) {
const encodedKey = Buffer.from(key).toString('base64');
encodedParams[encodedKey] = species[key];
}
const key = JSON.stringify(encodedParams);
let resultat;
let isCached = false;
const cachedResponse = await redisClient.get(key);
if (cachedResponse) {
isCached = true;
const decodedResponse = Buffer.from(cachedResponse, 'base64').toString('utf-8');
resultat = JSON.parse(decodedResponse);
res.send({
fromCache: isCached,
data: resultat
});
console.log(cachedResponse);
} else {
const responseData = await fetchApi(keys.join('/'));
const encodedResponseData = Buffer.from(JSON.stringify(responseData)).toString('base64');
redisClient.SETEX(key, 3600, encodedResponseData);
res.send(responseData);
}
}
app.post("/fish", getSpeciesData);
app.listen(port, () => {
console.log(`Listening on ${port}`);
});
I've tried to post a photo on instagram, but I've got an Bad Request error. Is that package fault or mine?
Code:
// modules
const config = require("./config.json");
const createPost = require("./canvas");
const fs = require('fs');
// db
const { QuickDB } = require('quick.db');
const db = new QuickDB();
// instagram
const { IgApiClient } = require('instagram-private-api');
const { sample } = require('lodash');
const ig = new IgApiClient();
ig.state.generateDevice(config.instagramUsername);
// tellonym
const Tellonym = require('tellonym-api');
const client = new Tellonym.login(config.tellonymToken);
// variabls
let tells = [];
// main code
setInterval(async () => {
client.getQuestions(20).then(response => {
response.forEach(async tell => {
if (tell.type === 'tell')
{
tells.push(tell.tell);
if(JSON.parse(JSON.stringify(await db.get('tells'))).strings[0].includes(tell.tell)) return;
await createPost(tell.tell);
await ig.simulate.preLoginFlow();
const loggedInUser = await ig.account.login(config.instagramUsername, config.instagramPassword);
process.nextTick(async () => await ig.simulate.postLoginFlow());
const post = await ig.publish.photo(
{
"file": fs.readFileSync("./output.png")
}
);console.log(post)
}
});
db.set("tells", {strings: [tells]});
});
}, 0.1 * 1000 * 60);
Error:
C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126
return new errors_1.IgResponseError(response);
^
IgResponseError: POST /rupload_igphoto/1671729786445_0_4886961932 -
400 Bad Request;
at Request.handleResponseError (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126:16)
at Request.send (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:54:28)
at async UploadRepository.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\repositories\upload.repository.js:18:26)
at async PublishService.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\services\publish.service.js:80:31)
at async C:\Users\PC\Desktop\spotted\index.js:38:30
Node.js v19.2.0
I cannot able to validate the webhook response from the shopify by using the "crypto-js" package.
i am using: "Node.js, AWS-Lambda , crypto-js" and the following code to validate
var CryptoJS = require("crypto-js");
var getRawBody = require("raw-body");
var Buffer = require('buffer/').Buffer // note: the trailing slash is important!
exports.handler = async (event, context) => {
let hmac = event.hmac;
const bodyString = Buffer.from(event.body, "utf8").toString();
var bodyForVerification = bodyString.replace('/\\/g', '\\\\');
let firma = CryptoJS.HmacSHA256(bodyForVerification, "****");
var hashInBase64 = CryptoJS.enc.Base64.stringify(firma);
let calculatedHmacBase = hashInBase64.toString(CryptoJS.enc.hex);
if(hmac == calculatedHmacBase {
console.log("verificado");
}
};
The HMAC is different..
I use this middleware for my public and private apps on Shopify,
using crypto, it is deprecated but works fine for my code.
const crypto = require('crypto');
const verify = function (req, res, next) {
if (req.query.shop) {
if (!req.query.signature) {
return false;
}
console.log(req.query);
const signature = req.query.signature;
const sharedSecret = process.env.SHOPIFY_SHARED_SECRET;
const def = req.query;
delete def.signature;
const sortedQuery = Object.keys(def).map(key => `${key}=${Array(def[key]).join(',')}`).sort().join('');;
const calculatedSignature = crypto.createHmac('sha256', sharedSecret).update(sortedQuery).digest('hex');
if (calculatedSignature === signature) {
console.log('validated');
return next();
}
console.log('not validated');
return false;
}
};
module.exports = verify;
I am working on lex and I am trying to store user data in DynamoDB while using NodeJS
Here is my code:
'use strict';
const uuidV1 = require('uuid/v1');
const AWS = require('aws-sdk');
const promisify = require('es6-promisify');
const dynamo = new AWS.DynamoDB.DocumentClient();
module.exports.saveBookingToDatabase = function(Arrival_city, Departure_city, Flight_type, Phone_number){
console.log('saveBookingToDatabase');
const item = {};
item.bookingId = uuidV1();
item.arrivalCity = Arrival_city;
item.departureCity = Departure_city;
item.classType = Flight_type;
item.phone = Phone_number;
const params = {
TableName: 'airstallion',
Item: item
};
const putAsync = promisify(dynamo.put, dynamo);
return putAsync(params).then(() => {
console.log(`Saving ticket ${JSON.stringify(item)}`);
return item;
})
.catch(error => {
Promise.reject(error);
});
}
When i run the program is returning the following error
Since aws-sdk library supports promise, its not necessary to use es6-promisify library. Using node.js async/await we shall achieve the same use case.
'use strict';
const uuidV1 = require('uuid/v1');
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
module.exports.saveBookingToDatabase = async function(Arrival_city, Departure_city, Flight_type, Phone_number){
console.log('saveBookingToDatabase');
const item = {};
item.bookingId = uuidV1();
item.arrivalCity = Arrival_city;
item.departureCity = Departure_city;
item.classType = Flight_type;
item.phone = Phone_number;
const params = {
TableName: 'airstallion',
Item: item
};
try {
let result = await dynamo.put(params)
console.log(`Saving ticket ${JSON.stringify(item)}`);
return item;
} catch(e) {
throw (e)
}
}
I perform the following task, during the registration of users for the first few months we did not save images of users in Firebase Cloud Storage and took a link that was received from Facebook. Now faced with the problem that some links to images have become expired. Because of this, I decided to make the cloud function and run it once as a script, so that it went through to users who have only one link to the image (which means that this is the first link received from facebook), take the facebook user id and request current profile image. I got a json file with the given users from Firebase, then I get links for each user separately, if the user is deleted then I process this error in a separate catch so that it does not stop the work of other promises. But after running this cloud function, I ran into this error because of this, for almost all users this operation was not successful. Even I increased the memory size in cloud function to 2 gigabytes. Please tell me how it can be fixed?
{ Error: read ECONNRESET
at exports._errnoException (util.js:1018:11)
at TLSWrap.onread (net.js:568:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' }
My function
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const account_file = require('../account_file.json');
var FB = require('fb');
const path = require('path');
const imageDownloader = require('image-downloader');
const os = require('os');
const shortid = require('shortid');
const imageManager = require('../../lib/Images/image-manager.js');
module.exports = functions.https.onRequest((req, res) => {
const token = req.header('X-Auth-Token');
var errorsCount = 0;
return admin.auth().verifyIdToken(token)
.then(function(decodedToken) {
const adminID = decodedToken.uid;
console.log('adminID is', adminID);
const users = account_file['users'];
var fixPhotoPromises = [];
users.forEach(function(user) {
const userID = user['localId'];
const fixPhotoPromise = fixPhoto(userID).catch(error => {
console.log(error);
errorsCount += 1;
});
fixPhotoPromises.push(fixPhotoPromise);
});
return Promise.all(fixPhotoPromises);
}).then(results => {
console.log('results.length', results.length, 'errorsCount', errorsCount);
console.log('success all operations');
const successJSON = {};
successJSON["message"] = "Success operation";
return res.status(200).send(successJSON);
}).catch(error => {
console.log(error);
const errorJSON = {};
errorJSON["error"] = error;
return res.status(error.code).send(errorJSON);
});
});
function fixPhoto(userID) {
var authUser = {};
var filename = '';
return new Promise((resolve, reject) => {
return admin.auth().getUser(userID)
.then(userModel => {
const user = userModel.toJSON();
const facebookID = user['providerData'][0]['uid'];
const userID = user['uid'];
authUser = {'userID' : userID, 'facebookID' : facebookID};
const userImagesPromise = admin.database().ref()
.child('userImages')
.child(userID)
.once('value');
return Promise.all([userImagesPromise])
}).then(results => {
const userImagesSnap = results[0];
if (userImagesSnap.val() !== null && userImagesSnap.val() !== undefined) {
const userProfileImagesDict = userImagesSnap.val()['userProfileImages'];
const keys = Object.keys(userProfileImagesDict);
var userProfileImages = [];
keys.forEach(function(key){
const userProfileImage = userProfileImagesDict[key];
userProfileImages.push(userProfileImage);
});
if (userProfileImages.length > 1) {
const status = 'user has more than one image';
return resolve(status);
}
}
const facebookAppID = functions.config().facebook.appid;
const facebookAppSecret = functions.config().facebook.appsecret;
const facebookAccessPromise = FB.api('oauth/access_token', {
client_id: facebookAppID,
client_secret: facebookAppSecret,
grant_type: 'client_credentials'
});
return Promise.all([facebookAccessPromise]);
}).then(results => {
const facebookResult = results[0];
const facebookAccessToken = facebookResult['access_token'];
const profileImageURL = 'https://graph.facebook.com/' + authUser.facebookID + '/picture?width=9999&access_token=' + facebookAccessToken;
const shortID = shortid.generate() + shortid.generate() + shortid.generate();
filename = shortID + ".jpg";
const tempLocalFile = path.join(os.tmpdir(), filename);
const options = {
url: profileImageURL,
dest: tempLocalFile // Save to /path/to/dest/image.jpg
};
const imageDownloaderPromise = imageDownloader.image(options);
return Promise.all([imageDownloaderPromise])
}).then(results => {
const imageDownloaderResult = results[0];
const userID = authUser.userID;
const localImagePath = imageDownloaderResult['filename'];
const imageManagerPromise = imageManager.saveUserImageToCloudStorage(localImagePath, filename, userID);
return Promise.all([imageManagerPromise]);
}).then(results => {
const result = results[0];
return resolve(result);
}).catch(function(error) {
reject(error)
})
});
}
exports.saveUserImageToCloudStorage = function saveUserImageToCloudStorage(localImagePath, filename, userID) {
const bucketName = functions.config().googlecloud.defaultbacketname;
const bucket = gcs.bucket(bucketName);
const profileImagePath = path.normalize(path.join('userImages', userID, 'profileImages', filename));
const profileImageFile = bucket.file(profileImagePath);
return new Promise((resolve, reject) => {
bucket.upload(localImagePath, {destination: profileImagePath})
.then(() => {
const config = {
action: 'read',
expires: '03-01-2500'
};
const userRefPromise = admin.database().ref()
.child('users')
.child(userID)
.once('value');
return Promise.all([profileImageFile.getSignedUrl(config), userRefPromise])
}).then(function(results) {
const url = results[0][0];
const userSnap = results[1];
if (userSnap.val() === null || userSnap.val() === undefined) {
return resolve('user was deleted from database');
}
const userModel = userSnap.val();
const userCheckID = userModel['id'];
if (userCheckID !== userID) {
return reject("WARNING userCheckID !== userID");
}
// save to database
const userImagesRef = admin.database().ref().child('userImages')
.child(userID)
.child('userProfileImages')
.push();
const timeStamp = timestamp.now();
const imageModelID = userImagesRef.key;
const userImagesRefPromise = userImagesRef.update({
'path': url,
'id': imageModelID,
'fileName': filename,
'timeStamp': timeStamp
});
const userRef = admin.database().ref()
.child('users')
.child(userID)
.child('currentProfileImage');
const userRefPromise = userRef.update({
'path': url,
'id': imageModelID,
'fileName': filename,
'timeStamp': timeStamp
});
return Promise.all([userImagesRefPromise, userRefPromise]);
}).then(() => {
const successJSON = {};
successJSON["message"] = "Success operation";
return resolve(successJSON);
}).catch(function(error) {
return reject(error);
});
});
};
I added this code when init google cloud storage and I did not have this error anymore.
var gcs = require('#google-cloud/storage')({keyFilename: "service-account-credentials.json"});
gcs.interceptors.push({
request: function(reqOpts) {
reqOpts.forever = false
return reqOpts
}
});