I'm learning to program DApps and a question that came up is the difference between the API injected by Metamask and web3.js. As I understand it, MetaMask injects an object that has its own API, which has nothing to do with the web3.js library. Is this correct? And can I still use the web3.js library with MetaMask? In the latter case, how would I do it? If anyone can explain further about this difference, I would be grateful. Thanks!
web3
is an older implementation which still some clients might use,
window.ethereum
is the new api. since some clients still use web3
we should still check for it.
Metamask connects you to the blockchain. Blockchain consists of blocks of data and these blocks of data are stored on nodes. Without nodes, you cannot access blockchain data.
MetaMask allows connectivity to the Ethereum blockchain through the infrastructure available at Infura ( https://infura.io ). This allows users to interact with the blockchain without having to install any node locally. infura connects to to different nodes in a different environment, such as mainnet, rinkeby, ropsten, etc.
web3js or web3py libraries are not related to metamask web3. Metamask provides a provider to web3.js
library. This provider tells web3.js
library which network we are going to communicate with and then connects to a node in that network.
Once you get the provider, you instantiate a web3 instance:
const web3 = new Web3(provider);
then you create a contract instance
contract = new web3.eth.Contract(
Contract.abi,
Contract.address
);
Now with contract.methods
you can call the methods on the contract. Also web3js library provides too many util functions like hashing, converting units etc