4

Does anybody knows how to deploy smart contract with node/web3 and using unlocked metamask account. I mean over internet it is advised to use HDWalletProvider with mnemonic but I want that user that is on my website could deploy contract from personal metamask account (like this REMIX do at the moment: when push "deploy" contract then metamask pops up with my personal account)! I want same thing but from my webpage where users can deploy contracts from their personal account! Thank you

How to change provider to user users personal metamask account ?

const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const compiledContract = require('../build/deal.json');

// TODO >>> HOW TO CHANGE THIS PROVIDER TO GET ACCOUNT FROM UNLOCKED METAMASK (WHITCH IS USERS PERSONAL ACCOUNT)
const provider = new HDWalletProvider(
  'twelve words mnemonic twelve words mnemonic twelve words mnemonic twelve words mnemonic',
  'https://rinkeby.infura.io/v3/<key>'
);

let web3 = new Web3();
web3.setProvider(new 
web3.providers.HttpProvider('https://rinkeby.infura.io/v3/<key>')); // http://localhost:8545

(async () => { const accounts = await web3.eth.getAccounts();
  console.log(`Attempting to deploy from account: ${accounts[0]}`);
  const deployedContract = await new web3.eth.Contract(compiledContract.abi)
    .deploy({
      data: '0x' + compiledContract.evm.bytecode.object,
      arguments: [3, 5]
    })
    .send({
      from: accounts[0],
      gas: '2000000'
    });

  console.log(
    `Contract deployed at address: ${deployedContract.options.address}`
  );

  provider.engine.stop();
})();

1 Answer 1

3

From Metamask FAQ:

if (typeof web3 !== 'undefined') {
  // Use Mist/MetaMask's provider
  web3js = new Web3(web3.currentProvider);
} else {
  console.log('No web3? You should consider trying MetaMask!')
  // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
  web3js = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}

or, adapted to your code, should look like this:

if (typeof web3 !== 'undefined') {
  // Use Mist/MetaMask's provider
  web3 = new Web3(web3.currentProvider);
} else {
  // fallback - use Infura
  let web3 = new Web3(
    new Web3.providers.HttpProvider(
      "https://rinkeby.infura.io/v3/<key>"));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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