Skip to content

Instantly share code, notes, and snippets.

@sagar-barapatre
Last active April 26, 2022 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagar-barapatre/4fcc635cf9226f33ce52ec0784079074 to your computer and use it in GitHub Desktop.
Save sagar-barapatre/4fcc635cf9226f33ce52ec0784079074 to your computer and use it in GitHub Desktop.
Web3.js Boilerplate code
import NFTContractBuild from 'contracts/NFT.json';
import Web3 from 'web3';
let selectedAccount;
let isInitialized = false;
let nftContract;
let provider = window.ethereum;
// sample init function. This runs everytime we need to connect to blockchain.
const init = async () => {
// checking if the machine has metamask installed or not. If not return error.
if (typeof provider !== 'undefined') {
provider
.request({ method: 'eth_requestAccounts' })
.then((accounts) => {
selectedAccount = accounts[0];
console.log(`Selected account is ${selectedAccount}`);
})
.catch((err) => {
console.log(err);
return;
});
// simple event listener so that whenever a person changes it's account, it'll get notified.
window.ethereum.on('accountsChanged', function (accounts) {
selectedAccount = accounts[0];
console.log(`Selected account changed to ${selectedAccount}`);
});
}
// This is a piece of code that is being used from the ABI array NFTContractBuild.json generated using solidity file.
const web3 = new Web3(provider);
const networkId = await web3.eth.net.getId();
// For each contract we have to declare the contract using web3
nftContract = new web3.eth.Contract(
NFTContractBuild.abi,
NFTContractBuild.networks[networkId].address
);
isInitialized = true;
};
// function to get the balance of our account address(wallet)
export const GetOwnBalance = async () => {
if (!isInitialized) {
await init();
}
// const web2 = new Web3(provider);
const balance = await nftContract.methods
.getBalance(selectedAccount)
.call();
return balance;
};
var TransactionHash;
// function to send money to a particular account address
export const SendTransaction = async () => {
// e.preventDefault();
const to_Address = document.getElementById('to_Address').value;
const valueAmount = document.getElementById('valueAmount').value;
if (!isInitialized) {
await init();
}
const web2 = new Web3(provider);
TransactionHash = await web2.eth.sendTransaction(
{
from: selectedAccount.toString(),
to: to_Address.toString(),
value: valueAmount.toString(),
},
function (err, transactionHash) {
if (err) {
console.log(err);
} else {
TransactionHash = transactionHash;
}
}
);
return TransactionHash;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment