0 votes
1 view
in Blockchain by (12.8k points)

I was trying to use Infura API to make an Ethereum web app. First I compiled a solidity contract and then deployed it using infura api on rinkeby network. Here is my deploy script which seems to be running successfully.

const HDWalletProvider = require("truffle-hdwallet-provider");

const Web3 = require('Web3');

const compileFactory = require('./build/CampaignFactory.json');

const provider = new HDWalletProvider(

    "MY_SECRET_MNEMONIC",

    "https://rinkeby.infura.io/v3/363ea9633bcb40bc8a857d908ee27094"

);

const web3 = new Web3(provider);

console.log("provider info: " + provider);

const deploy = async () => {

    const accounts = await web3.eth.getAccounts();

    console.log("account used: " + accounts[0]);

    result = await new web3.eth.Contract(JSON.parse(compileFactory.interface))

        .deploy({data: "0x"+compileFactory.bytecode})

        .send({from: accounts[0]});

    console.log("deployed to address: " + result.options.address);

};

deploy();

Then I created another script web3.js which creates a web3 provider using Infura api:

import  Web3 from 'web3';

let web3;

if (typeof window !== 'undefined' && typeof window.web3!=='undefined') {

    // we are in the browser and metamask is running.

    web3 = new Web3(window.web3.currentProvider);

    console.log("using metamask");

}

else {

    // we are in server OR user without metamask.

    const provider = new Web3.providers.HttpProvider(

        "https://rinkeby.infura.io/v3/363ea9633bcb40bc8a857d908ee27094"

    );

    web3 = new Web3(provider);

    console.log("using infura");

}

export default web3;

but when I import this web3.js file somewhere and then try to use 'web3' object, it returns empty array of accounts. For example:

import web3 from '../../ethereum/web3';

...

const accounts = await web3.eth.getAccounts();

console.log("Account list: "+accounts); // returns empty array.

But ideally, it should return the accounts list associated with my mnemonic. What is the problem?

1 Answer

0 votes
by (29.8k points)

One solution that i can think of is to use the HDWalletProvider in your second script, instead of the HttpProvider

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...