1

I am new in Solidity. I'm trying to create a API in node js, which can be use without a navigator like chrome with MetaMask. I would like to test it with postman. But i have some problems with web to get accounts. Actually it returns me en empty array. And I show you my code, if you have some better way to create my api, like good practice i take it.

this is my web3.js :

var Web3 = require('web3');

let web3;

if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
    web3 = new Web3(window.web3.currentProvider);
} else {
    const provider = new Web3.providers.HttpProvider(
        'https://rinkeby.infura.io/v3/913ea7dd990444a58cc903fb97acc4a8'
    );
    web3 = new Web3(provider);
}

module.exports = web3;

and this is my server.js api

var express = require("express");
var app = express();
const factory =  require('./ethereum/factory.js');
const web3 = require('./ethereum/web3');
const contract = factory.contract;
const { check, validationResult } = require('express-validator');

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

app.post("/mandat", [
    check('firstname').isLength({ min: 1 }).isAlphanumeric(),
    check('lastname').isLength({ min: 1 }).isAlphanumeric(),
    check('hash').isAlphanumeric(),
    check('budget').isInt(),
    check('located').isLength({ min: 1 }).isAlphanumeric(),
  ], async (req, res) => { 

    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })
    }
    const firstname  = req.body.firstname;
    const lastname = req.body.lastname;
    const hash = req.body.hash;
    const budget = req.body.budget;
    const located = req.body.located;
    const signedDate = req.body.signedDate;

    const accounts = await web3.eth.getAccounts();
    console.log(accounts[0]);
    try {
        await contract.methods.createMandat(lastname, firstname, hash, "fefe", located, "fsfsfs", "a").send({
            from: accounts[0]
        });
    } catch (err) {
        res.json({message : "La creation du mandat a echouer avec l'erreur suivante : '" + err.message + "'"})
    }

    res.json({message : "Creation d'un mandat reussie, la cle pour obtenir l'adresse est " + "a"});
});

app.get("/mandat", async (req, res) => {
    const index = req.query.index;
    try {
        const result = await contract.methods.getOneDeployedMandat(index).call();

    } catch (err) {
        res.json({message : "La recuperation des donnes du mandat a echouer avec l'erreur suivante : '" + err.message + "'"})
    }
});

In my first route in post, getAccounts return me an empty array.

In my second routes in get, the method in contract return 6 variables, but i don't know how to get them.

Thanks you for your help and sorry for my bad english

0

Account management is a stateful function and is not supported by Infura (you would expose your accounts to other Infura users and they would steal your money).

What you can do is that you set up your Web3.js accounts in a such a way that they come from known private keys. We can do this by using HDWalletProvider from Truffle to manage accounts on your local web3.js instance, not on the node side.

Here is an example:

  // Be explicit on our connection options so we
  // can better understand situations like timeouts
  // TODO: FUTURE! https://github.com/ethereum/web3.js/pull/3190
  const wsOptions = {
    timeout: 5000,
  };

  assert(infuraProjectId, 'Infure project id missing');
  const rpcURL = `wss://${network}.infura.io/ws/v3/${infuraProjectId}`;

  console.log('Connecting to Infura endpoint', rpcURL);

  const connectionProvider = new Web3WsProvider(rpcURL, wsOptions);

  // Any keys you wish to use. 
  // MAKE SURE THESE HAVE 0x PREFIX FOR THE HEX VALUES
  const zeroExPrivateKeys = ["0x1111111..."];

  // We need this to not to trigger server-side eth_send RPC
  // that is not supported by Infura.
  // Instead, HDWalletProvider will sign transactions locally
  // using imported private key.
  const walletProvider = new HDWalletProvider(zeroExPrivateKeys, connectionProvider);
  console.log('Loaded private keys for addresses', walletProvider.getAddresses());

  web3 = new Web3(walletProvivder);

Full example

Also see how to generate private keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.