Calling a smart contract function using truffle/hdwallet-provider - javascript

I have a contract on polygon and I want to call a write function setPrice(uint256 _price) but when I run this code then I am getting an error:
{ code: -32000, message: 'transaction underpriced' }
Smart Contract: https://polygonscan.com/address/0x8835c31178f8f3407d4588be49532de1c02c3a04
this is my code:
const Web3 = require("web3");
const WalletProvider = require("#truffle/hdwallet-provider");
const http = require("http");
const { release } = require("os");
const mysql = require('mysql');
const conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"nft",
});
conn.connect(function(err) {
if (err) throw err;
//console.error("Connected!");
});
let provider = new WalletProvider({
mnemonic: {
phrase: '*****myWalletPhrase*****'
},
providerOrUrl: "https://rpc-mainnet.matic.quiknode.pro/"
});
const web3 = new Web3(provider);
const dexABI ="smartContractAbi";
const contract_address = "0x8835c31178F8f3407d4588Be49532De1c02C3A04";
const contract = new web3.eth.Contract(dexABI, contract_address);
function toFixed(x) {
// some code
}
http.createServer(async (req, res) => {
if(req.url != '/favicon.ico')
{
try {
const accounts = await web3.eth.getAccounts();
//console.error(accounts);
let user= accounts[6];
let amount=0;
conn.query(`SELECT * FROM dollor_rate`, async function(err,result){
if (err) return err;
console.error("this",result[0].usd_rate);
amount=toFixed(result[0].usd_rate).toString();
await contract.methods.setPrice(''+amount).send({from:user,gas:21000},function(err1,receipt){
if(err1)
console.error("Error==>",err1);
else
console.error("Erorr1=======",receipt);
});
});
} catch (error) {
console.log(error);
}
res.end();
}
})
.listen(8080);

The gas fee you are providing with the transaction is low. Try increasing the gas you provide with the transaction.
This is similar to this,
https://stackoverflow.com/a/67974018/7453857

Related

How to fix "ConnectionError: Connection is closed" on Node.js with MSSQL?

I'm having issues with SQL server. Every time I try to run this server and get the results from database, I got this error message:
ConnectionError: Connection is closed.
...
code: 'ECONNCLOSED'
I can't find any way to fix this, is there something missing I should have on my JS files?
connection.js
const sql = require('mssql/msnodesqlv8');
const dbSettings = {
user: '******',
password: '******',
server: "DESKTOP-*****\\SQLEXPRESS",
database: 'webstore',
driver: 'msnodesqlv8',
options: {
encrypt: true, // for azure
}
}
export async function getConnection() {
try {
const pool = await sql.connect(dbSettings, function(err) {
if(err) {
console.log(err);
}
});
return pool;
} catch (error) {
console.log(error);
}
}
products.controller.js
import {getConnection} from '../database/connection';
export const getProducts = async (req, res) => {
const pool = await getConnection();
const result = await pool.request().query('SELECT * FROM Products');
console.log(result);
res.json('products');
};

I am connect mongo atlas with this code, but cannot create the database when i send these data

const { MongoClient } = require("mongodb");
const url =
"mongodb+srv://user:password#cluster0.25pjvgx.mongodb.net/products_test?retryWrites=true&w=majority";
const createProduct = async (req, res, next) => {
const newProduct = {
name: req.body.name,
price: req.body.price
};
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db();
const result = db.collection('products').insertOne(newProduct);
} catch (error) {
return res.json({message: 'Could not store data.'});
};
client.close();
res.json(newProduct);
};
const getProducts = async (req, res, next) => {};
exports.createProduct = createProduct;
exports.getProducts = getProducts;
send--
{
"name":"apple",
"price": 99
}
output-
{
"message": "Could not store data."
}
Where is the problem? I try to send the data to the database. But it doesn't work I can not find. please help me.
i used await before db.collection('products').insertOne(newProduct).It works for me

Status Code 502 - Server Error - Node.js Express & MongoDB - Incomplete response received from application

I've noticed that in my application, some pages show a status code 304 whereas some other ones show a status code 200.
Besides that, there is a page that is not displaying on production mode and shows a status code 502.
Why there is such differences in my application for the pages that are working, but showing a status code 304 and 200?
Moreover, why my blog page is not displaying on production mode and shows the status code 502 and displays the following message:
Incomplete response received from application
Though, the blog page is displaying well on development mode and shows the status code 304.
Is there any relation between the status code 304 in development and the status code 502 in production mode?
I mean, the status code 304 in development mode could be the reason for the error and the status code 502 in production mode?
Below is my code.
app.js:
const path = require('path');
const express = require('express');
const session = require('express-session');
const sessionConfig = require('./config/session');
const db = require('./data/database');
const adminRoutes = require('./routes/admin/blog');
const authRoutes = require('./routes/admin/auth');
const defaultRoutes = require('./routes/home/default');
const postsRoutes = require('./routes/home/posts');
const quotationsRoutes = require('./routes/home/quotations');
const contactsRoutes = require('./routes/home/contacts');
const authMiddleware = require('./middlewares/auth-middleware');
const mongoDbSessionStore = sessionConfig.createSessionStore(session);
let port = 3000;
if (process.env.MONGODB_URL) {
port = process.env.MONGODB_URL;
}
const app = express();
app.set('views', [
path.join(__dirname, 'views/home'),
path.join(__dirname, 'views/admin')
]);
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use('/public/admin/images', express.static('public/admin/images'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(session(sessionConfig.createSessionConfig(mongoDbSessionStore)));
app.use(authMiddleware);
app.use('/', adminRoutes);
app.use('/', authRoutes);
app.use('/', defaultRoutes);
app.use('/', postsRoutes);
app.use('/', quotationsRoutes);
app.use('/', contactsRoutes);
app.use(function (req, res) {
res.status(404).render('404');
});
app.use(function (error, req, res, next) {
console.error(error);
res.status(500).render('500');
});
db.connectToDatabase()
.then(function () {
app.listen(port);
})
.catch(function (error) {
console.log('La connexion à la base de données a échoué !');
});
routes\home\posts.js:
const express = require('express');
const mongodb = require('mongodb');
const xss = require('xss');
// const uuid = require('uuid');
const db = require('../../data/database');
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/blog', blogControllers.getBlog);
router.get('/blog/:id', blogControllers.getBlogId);
router.get('/blog/:id/comments', blogControllers.getBlogIdComments);
router.post('/blog/:id/comments', blogControllers.postBlogIdComments);
router.get('/profile', blogControllers.getProfile);
module.exports = router;
routes\admin\blog.js:
const express = require('express');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storageConfig });
const blogControllers = require('../../controllers/post-controllers');
const router = express.Router();
router.get('/posts', blogControllers.getPosts);
router.get('/new-post', blogControllers.getNewPost);
router.post('/new-post', upload.single('image'), blogControllers.postNewPost);
router.get('/blog/:id/edit', blogControllers.getBlodIdEdit);
router.post('/blog/:id/edit', blogControllers.postBlogIdEdit);
router.post('/blog/:id/delete', blogControllers.postBlogIdDelete);
router.get('/admin', blogControllers.getAdmin);
module.exports = router;
models\post.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const ObjectId = mongodb.ObjectId;
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
if (id) {
this.id = new ObjectId(id);
}
}
static async fetchAll() {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, content: 1, 'author.name': 1 })
.toArray();
return posts;
}
async fetch() {
if (!this.id) {
return;
}
const postDocument = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(this.id) },
{ title: 1, summary: 1, content: 1 }
);
this.title = postDocument.title;
this.summary = postDocument.summary;
this.content = postDocument.content;
}
async save() {
let result;
if (this.id) {
result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: this.id },
{
$set: {
title: this.title,
summary: this.summary,
content: this.content
}
}
);
} else {
result = await db.getDb().collection('posts').insertOne({
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
});
}
return result;
}
async delete() {
if (!this.id) {
return;
}
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: this.id });
return result;
}
}
module.exports = Post;
controllers\post-controllers.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const Post = require('../models/post');
const ObjectId = mongodb.ObjectId;
async function getBlog(req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({
title: 1,
summary: 1,
content: 1,
'author.name': 1,
imagePath: 1
})
.toArray();
console.log(posts);
res.render('posts', { posts: posts });
}
async function getBlogId(req, res, next) {
let postId = req.params.id;
try {
postId = new ObjectId(postId);
} catch (error) {
return res.status(404).render('404');
// return next(error);
}
const post = await db
.getDb()
.collection('posts')
.findOne({ _id: postId }, { summary: 0 });
if (!post) {
return res.status(404).render('404');
}
post.humanReadableDate = post.date.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
});
post.date = post.date.toISOString();
res.render('post-detail', { post: post, comments: null });
}
async function getBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const comments = await db
.getDb()
.collection('comments')
.find({ postId: postId })
.toArray();
res.json(comments);
}
async function postBlogIdComments(req, res) {
const postId = new ObjectId(req.params.id);
const newComment = {
postId: postId,
title: xss(req.body.title),
text: xss(req.body.text)
};
await db.getDb().collection('comments').insertOne(newComment);
res.json({ message: 'Commentaire ajouté !' });
// res.status(500).json({ message: 'Error!' });
}
function getProfile(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
res.render('profile');
}
async function getPosts(req, res) {
const posts = await Post.fetchAll();
res.render('posts-list', { posts: posts });
}
async function getNewPost(req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
}
async function postNewPost(req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
}
async function getBlodIdEdit(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.fetch();
if (!post.title || !post.summary || !post.content) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
}
async function postBlogIdEdit(req, res) {
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
...[, , ,], // pass 3 undefined arguments
req.params.id
);
await post.save();
res.redirect('/posts');
}
async function postBlogIdDelete(req, res) {
const post = new Post(null, null, null, null, null, null, req.params.id);
await post.delete();
res.redirect('/posts');
}
async function getAdmin(req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
}
module.exports = {
getBlog: getBlog,
getBlogId: getBlogId,
getBlogIdComments: getBlogIdComments,
postBlogIdComments: postBlogIdComments,
getProfile: getProfile,
getPosts: getPosts,
getNewPost: getNewPost,
postNewPost: postNewPost,
getBlodIdEdit: getBlodIdEdit,
postBlogIdEdit: postBlogIdEdit,
postBlogIdDelete: postBlogIdDelete,
getAdmin: getAdmin
};

How to use .then method for promises with mySQL?

I know that mongodb has their own way of handling native promises with no rejection issues but I guess it doesnt work the same here with mysql. Is there anyway I can use .then in mysql? I was able to do it using more callbacks but I would like to use promises to make the solution cleaner or even use async/await if that makes it simpler too. I need to use a callback to jump to my server file, I have all my methods defined in my db file.
Server file:
app.get('/api/cows', (req, res) => {
db.reqMethods.getAll((err, data) => {
if (err) {
res.send('Error');
} else {
res.send(data);
}
});
});
db file:
const mysql = require('mysql');
const http = require('http');
const express = require('express');
const path = require('path');
const bodyParser = require("body-parser");
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'cowlist'
});
connection.connect((err) => {
if (err) {
console.log(err);
} else {
console.log('Connected to MySQL!')
}
});
// Your Database Queries Here!!
module.exports.reqMethods = {
// GET All Cow Info
getAll: function (callback) {
const query = connection.query('SELECT * FROM cows;');
query.then(data => callback(null, data));
});
};
// callback solution that I'd like to simplify:
// getAll: function (callback) {
// connection.query('SELECT * FROM cows;', (err, data) => {
// if (err) {
// callback(err, null);
// } else {
// console.log("DATA: \n", data);
// callback(null, data);
// }
// });
// }
Yes, this is possible by using mysql2 npm package.
So in your database.js file, use this method.
const mysql = require('mysql2');
var pool_connection = mysql.createPool({
host: '127.0.0.1',
port: 3306,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
connectionLimit: 10,
multipleStatements: true
});
pool_connection.getConnection((err) => {
if (err) console.log(JSON.stringify(err));
else {
console.log('Connected!')
}
});
module.exports = pool_connection.promise();
And in your models, you require the connection as follows and make use of async-await in a try-catch block.
const con = require('/path/to/your/database_file');
module.exports = class Messages {
constructor() { }
static async getMessage(arguments_here) {
const query = "some query here with params if required. Use ? for placing params and do not use string literal to embed params.";
try {
const [response] = await con.execute(query, [params]);
return response;
} catch (error) {
console.log(error);
return null;
}
}
}
And in your controller,
const Messages = require('../models/Messages');
const someFn = async (req, res) =>{
try {
const result = await Messages.getMessages('sample_arguments');
//do something with result
}
catch(err){
console.log(err);
}
}

How to modify common mongodb query to async with try and catch

This is my code with written with express js
this query works but I think that using async is more reliable than this
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
const client = new MongoClient(url, { useUnifiedTopology: true });
app.get("/", async (req, res) => {
// this is myquery code with right result
client.connect((err) => {
assert.equal(null, err);
const db = client.db(db_n)
db.collection("list").find({}).toArray((err, result) => {
if(err) throw res.send({ status: "Error when react data", bool: false}).status(450);
res.send(result).status(200);
})
})
});
Try this, not exactly the same as yours, but will give you the idea on how to use async/await with try/catch
const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
const client = new MongoClient(url, { useUnifiedTopology: true });
app.get('/', async (req, res) => {
// Connect client if it's not connected
if(!client.isConnected()) {
await client.connect();
// you can also catch connection error
try {
await client.connect();
catch(err) {
return res.status(500).send();
}
}
const db = client.db(db_n);
try {
// Run queries
const result = db.collection("list").find({});
res.json(await result.toArray());
} catch (err) {
// Catch any error
console.log(err.message);
res.status(450).send();
}
});
I have not tested this, but try something along the lines of:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = "mongodb://localhost:27017/nodejs_crud";
const db_n = "nodejs_crud"
let client;
const getDb = async () => {
// If we don't have a client, create one.
if (!client) client = new MongoClient(url, { useUnifiedTopology: true });
// If we are not connected, then connect.
if (!client.connected()) await client.connect();
// Get our database
return client.db(db_n);
}
app.get("/", async (req, res) => {
try {
const db = await getDb();
const results = await db.collection("list").find({}).toArray();
res.send(result).status(200);
} catch (err) {
res.send({ status: "Error when react data", bool: false}).status(450);
}
});

Categories