In Ethereum dApps, You can use Metamask with the latest Web3.js version. AND you can use at the same time the old version. Why and how ?

Using Web3.js with Metamask NOW

Web3.js version 1.0.0 is way better than the old version in many areas. One that I very much like is the PromiEvent. Basically, this allows you for instance to follow the whole lifecycle on the blockchain of an Ethereum transaction. That's awesome. When coupled with React.js (for instance), that's even more amazing.

But as of now, Metamask injects the good old 0.20.x version of Web3.js and those new cool features aren't in it.

In fact, it's very easy to use the latest build of Web3 1.0.0, while keeping the accounts management and the Node proxy of Metamask. At first download a release of the latest build of Web3.js 1.0.0. Then load it:

...
    <script src="web3.js"></script>
  </body>
</html>

Replace the old version injected by Metamask by the brand new, while keeping the accounts management and node :

// If the browser has injected Web3.js
if (window.web3) {
  // Then replace the old injected version by the latest build of Web3.js version 1.0.0
  window.web3 = new Web3(window.web3.currentProvider);
}

At last you use it like in the Web3.js 1.0.0 documentation. As for example, you can now use the great PromitEvent I was talking about earlier:

const myContract = new window.web3.eth.Contract (
  myContractAbi,
  myContractAddress
);
...
myContract.methods.myMethod().send()
.on('transactionHash', function(hash){
  ...
})
.on('receipt', function(receipt){
  ...
})
.on('confirmation', function(confirmationNumber, receipt){
  ...
})
.on('error', console.error);

That's it!

AND use the good old injected Web3.js

Oh, I'm hearing critics over there:

It's cool, but now I can't subscribe to events and watch() anything on the blockchain!!! I could do it with the injected Web3.js of Metamask, this sucks!!! If only we could have the best of both at the same time, and now!

Yes we can ;)

// If the browser has injected Web3.js
if (window.web3) {
  // Then backup the good old injected Web3, sometimes it's usefull:
  window.web3old = window.web3;
  // And replace the old injected version by the latest build of Web3.js version 1.0.0
  window.web3 = new Web3(window.web3.currentProvider);
}

Now you can use again all the good old cool watch features that are not yet available in Metamask with Web3.js 1.0.0, like:

const myContractOldWeb3Object = window.web3old.eth.contract (myContractAbi));
const myContractOldWeb3 = myContractOldWeb3Object.at (myContractAddress),
var myEvent = myContractOldWeb3.MySolidityEvent();
myEvent.watch (
  (err, event) => {
    if (err) console.error (err);
    else {
      ... do something with event
    }
  }
);

Happy coding!

Add new comment

Comment