I am making a small token project with front-end website to ease the use. The architecture is Ethereum private network with ERC20 contract, PostgreSQL to associate address with alias of wallet, NodeJS and AngularJS.
I am very new to Javascript Promises and I struggled a lot in the past few months to understand how to use them "properly".
What follows is the code for my ExpressJS endpoints. It is working, but could you tell me whether I am doing things properly?
Another question: I would like to move the initialisation of sequelize, web3 and truffle on another js file. I tried with require() but variables become undefined; what should I do?
const express = require('express');
const path = require('path');
const Web3 = require('web3');
const fs = require('fs');
const TruffleContract = require('truffle-contract');
const Sequelize = require('sequelize');
const Aigle = require('aigle');
const router = express.Router();
const Op = Sequelize.Op;
const sequelize = new Sequelize('aircoin', 'giuseppe', '12345', {
dialect: 'postgres',
host: "localhost",
port: 5432,
operatorsAliases: false
});
let web3;
let contract;
if (typeof web3 !== 'undefined') {
web3Provider = web3.currentProvider;
} else {
web3Provider = new Web3.providers.HttpProvider('localhost:8545');
}
web3 = new Web3(web3Provider);
fs.readFile(path.resolve(__dirname, 'TokenERC20.json'), 'UTF-8', function read(err, res) {
if (err) {
throw err;
}
data = JSON.parse(res);
contract = new TruffleContract(data);
contract.setProvider(web3Provider);
});
router.get('/', function(req, res, next) {
res.sendFile('index.html');
});
router.get('/api/v1/wallet/:ens', function(req, res){
const name = req.params.ens.replace(" ", "_");
let result = [];
const iterator = function(value, num, collection) {
return contract
.deployed()
.then(function(deployed) {
return deployed.balanceOf(value.address);
})
.then(function(data) {
return data.toNumber() / Math.pow(10, 18);
})
.then(function(data) {
return result.push({ address: value.address, name: name, balance: data });
})
.catch(function(err) {
console.log(err.message);
});
return Promise.resolve(null);
};
return sequelize.query('SELECT address FROM ens WHERE UPPER(name) LIKE UPPER($1);', { bind: [name], raw: true, type: Sequelize.QueryTypes.SELECT })
.then(function(row) {
return Aigle.resolve(row).each(iterator);
})
.then(function() {
return res.json(result);
})
.catch(function(err) {
console.log(err.message);
});
//return Promise.resolve(null);
});
router.get('/api/v1/wallet', function(req, res){
let result = [];
const iterator = function(value, num, collection) {
return contract
.deployed()
.then(function(deployed) {
return deployed.balanceOf(value.address);
})
.then(function(data) {
return data.toNumber() / Math.pow(10, 18);
})
.then(function(data) {
return result.push({ address: value.address, name: value.name, balance: data });
})
.catch(function(err) {
console.log(err.message);
});
return Promise.resolve(null);
};
return sequelize.query('SELECT address, name FROM ens;', { raw: true, type: Sequelize.QueryTypes.SELECT })
.then(function(row) {
return Aigle.resolve(row).each(iterator);
})
.then(function() {
return res.json(result);
})
.catch(function(err) {
console.log(err.message);
});
//return Promise.resolve(null);
});
router.post('/api/v1/wallet', function(req, res){
const data = { name: req.body.name.replace(" ", "_"), passphrase: req.body.passphrase };
const address = web3.personal.newAccount(data.passphrase);
const bank = "0x49b36fa1772bdb4d9249f43179832ccdb3732ffc";
web3.personal.unlockAccount(bank, "", function(error, res) {
if (error) {
console.log(error.message);
return;
}
var amount = web3.toWei(3.20, "ether")
web3.eth.sendTransaction({ from: bank, to: address, value: amount })
});
return sequelize.query('INSERT INTO ens (address, name) VALUES ($1, $2);', { bind: [address, data.name], raw: true, type: Sequelize.QueryTypes.INSERT })
.then(function() {
return res.status(200).json({ address: address });
});
//return Promise.resolve(null);
});
router.post('/api/v1/transaction', function(req, res){
const data = { from: req.body.from.replace(" ", "_"), passphrase: req.body.passphrase, to: req.body.to.replace(" ", "_"), amount: req.body.amount*10**18 };
let result = {};
const iterator = function(value, num, collection) {
return result[value.name] = value.address;
};
return sequelize.query('SELECT address, name FROM ens WHERE UPPER(name) LIKE UPPER($1) OR UPPER(name) LIKE UPPER($2);', { bind: [data.from, data.to], raw: true, type: Sequelize.QueryTypes.SELECT })
.then(function(row) {
return Aigle.resolve(row).each(iterator);
})
.then(function() {
return web3.personal.unlockAccount(result[data.from], data.passphrase)
})
.then(function() {
return contract.deployed()
})
.then(function(deployed) {
return deployed.transfer(result[data.to], data.amount, { from: result[data.from] });
})
.then(function(tx) {
console.log(tx);
return res.status(200).json(tx);
})
.catch(function(err) {
console.log(err.message);
return res.status(500).json(err);
});
//return Promise.resolve(null);
});
module.exports = router;