Wallet Setup
Set up a wallet for contract deployment and execution
Developers can manage Ethereum wallet private keys using the MetaMask browser add-on.
MetaMask is a non-custodial wallet. The user's private key is encoded with the mnemonic phrase and stored in user's local browser. Once lost, the user can no longer control the savings or restore access to the wallet. MetaMask communicates with Ethereum Ledger via Infura. Please refer to the MetaMask website for more details.
First, install the following in your dApp:
npm install --save web3
Create a new file, name it web3.js and insert the following code in it:
import Web3 from 'web3';
const getWeb3 = () => new Promise((resolve) => {
window.addEventListener('load', () => {
let currentWeb3;
if (window.ethereum) {
currentWeb3 = new Web3(window.ethereum);
try {
// Request account access if needed
window.ethereum.enable();
// Accounts now exposed
resolve(currentWeb3);
} catch (error) {
// User denied account access...
alert('Please allow access for the app to work');
}
} else if (window.web3) {
window.web3 = new Web3(web3.currentProvider);
// Accounts always exposed
resolve(currentWeb3);
} else {
console.log('Non-Ethereum browser detected. You should consider trying MetaMask!');
}
});
});
export default getWeb3;
To put it simply, you can inject the global object
ethereum
if you have added MetaMask to Chrome.Next, import the code as below:
import getWeb3 from '/path/to/web3';
Call the function:
getWeb3()
.then((result) => {
this.web3 = result;// we instantiate our contract next
});
We need an account from the web3 instance we created above to send transactions.
this.web3.eth.getAccounts()
.then((accounts) => {
this.account = accounts[0];
})
The
getAccounts()
function returns all the user’s Metamask accounts, whileaccounts[0]
is the one currently selected by the user.Initialize your contract after completing above steps.
Now you can call any function by directly interacting with the instantiated contract. Please note that:
Functions that do not alter the state of the contract are
call()
functions. Below is an example of calling a call()
function: this.myContractInstance.methods.myMethod(myParams)
.call()
.then(
// do stuff with returned values
)
Functions that alter the state of the contract are
send()
functions. Below is an example of calling a send()
function:this.myContractInstance.methods.myMethod(myParams)
.send({
from: this.account,gasPrice: 0
}).then (
(receipt) => {
// returns a transaction receipt}
);
Last modified 1yr ago