How to do it...

Now, we will start with the steps that are needed to use MetaMask as an injected provider:

  1. Initialize web3 using the provider object injected by the browser providers:
// For v0.2x.x
var web3 = new Web3(web3.currentProvider);

// For v1.x.x
var
web3 = new Web3(Web3.givenProvider);
  1. Check for existing providers to ensure that you are not overwriting the existing Mist or MetaMask provider:
// For v0.2x.x
if
(typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(
new Web3.providers.HttpProvider("http://localhost:8545")
); }

// For v1.x.x
var web3 = new Web3(Web3.givenProvider || "ws://localhost:8546");
MetaMask cannot communicate to applications running directly from a filesystem through file://. This is because of the security restrictions in the browser. Run a local server during development to avoid this issue.
  1. Use asynchronous callbacks to read data from Ethereum via providers. This is because the browser does not have the full blockchain in local and MetaMask has to get the data from a remote server:
// For v0.2x.x
web3.eth.getBalance(<address>, function (error, result) {
if (!error) {
console.log(result);
}
});

// For v1.x.x
web3.eth.getBalance("<address>").then(console.log);
There are some exceptions to asynchronous commands in MetaMask. The following methods can return value synchronously: web3.eth.accountsweb3.eth.coinbaseweb3.eth.uninstallFilterweb3.eth.reset, and web3.version.network.
  1. MetaMask also handles user accounts and private keys. Any time you make a transaction (Ether transfer or contract call), MetaMask will automatically prompt the user for permission. Based on the user input, it will forward the call to the Ethereum node. This avoids the need to sign and send the transaction from the application.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.27.72