Posted By : Jagveer
A Smart Contract is a transaction protocol that is self-executing as per the terms of an agreement between seller and buyer, existing on a blockchain platform. Most smart contracts are stored on the Ethereum blockchain. The smart contract codes control all the transactions on a blockchain, and execution is trackable and irreversible. All smart contracts written in smart contract-specific programming languages are compiled in bytecode.
Solidity is a language that we can use to code smart contracts code. Smart contract syntax is very similar to Javascript, and EVM (Ethereum Virtual Machine) is used to read and execute the Smart Contract. We can execute the solidity programs by using an online IDE (integrated development environment) called Remix or local machines.
Step 1:- First we need to add/install the Metamask extension in any browser like Google Chrome, Firefox, etc.
Step 2:- Web3.js is the official Ethereum JavaScript API and it is used to interact with Ethereum smart contract.
Step 3:- In this step, we are connecting the MetaMask wallet with a dApp. If the user's wallet is in lock status then it will ask for unlocking Metamask wallet, otherwise, it will directly connect the user's Metamask wallet with the dApp application.
async function connectWallet() {
if (window.ethereum) {
window.web3 = new Web3(window.ethereum); }
conn = await window.ethereum.enable();
ethconnected = conn.length > 0
if (ethconnected) {
ethaddress = conn[0] // get wallet address
}
web3.eth.getAccounts().then(console.log);
return true;
}
Step 4:- In this step, we are creating a contract object with the help of a web3 object and we will use this contract object to call Ethereum smart contract methods.
contract = new web3.eth.Contract(<contract Abi>, <contract address>);
Step 5:- In this step, we are calling the balanceOf() method of smart contract to get user balance.
You may also like to read | How to use Blockchain in the Metaverse | Oodles Blockchain
contract.methods.balanceOf(ethaddress).call().then(function (balance) {
console.log(balance);
})
Step 6:- In this step, we are calling the add() method of smart contract to add two numbers and after successful transaction creation, it will return you a transaction hash value. You can use this transaction hash value to check the transaction status on etherscan.io.
contract.methods.add("10", "20").send({ from: ethaddress }, async function (error, transactonHash) {
console.log(transactonHash);
})
This is a simple example to interact with an Ethereum smart contract by using the Web3.js library and this can only be checked in a local environment.
For more information about Ethereum smart contracts development, you may connect with our skilled smart contract developers.
November 21, 2024 at 12:01 pm
Your comment is awaiting moderation.