How To Connect a Web3 Ethereum Smart Contract to your Frontend using Solidity, Web3, Metamask, Remix & Express
In this article we will build, deploy and return our decentralized Ethereum blockchain smart contract to our frontend.
The first time I heard of a smart contract was in 2017 when I was first introduced to cryptocurrency. Bitcoin was blowing up from $1000 to $20,000 that year...
When BTC pumps, it brings the market value all of the other projects up with it.
One of those projects that I learned about was Ethereum.
In the context of this article, we are learning about smart contracts on Ethereum.
When you deploy a contract onto the Ethereum blockchain thousands of computers around the world work together to secure the network because they are paid gas fees to do so.
Ethereum is a technology that's home to digital money, global payments, and applications.
So for people to interact with your smart contracts on a frontend, you need to be very careful that your code is super efficient.
This is because every time a function from your contract is called using your web3 frontend, gas is required to run those functions.
This would cost real ETH on the Mainnet once deployed.
This is why we use testnets to test our projects against the frontend, sending transactions, deploying, calling functions etc...
On testnets you can use an Ethereum faucet to send free testETH to your metamask wallet to test with. We will be using the Sepolia Ethereum Testnet.
So if you want to build a Web3 project you will most likely need to build a frontend to be able to interact with this contract that lives on the Ethereum network.
This was a tutorial that I found on Youtube but I've had to modify it so that it works for me as buddy had different dependencies and some of his code didn't work.
In this article you will learn how to use:
First install dependencies
Node.js needs to be installed on your machine first.
Install Express.js with "npm install express".
Step 1 - Build & deploy the smart contract with Remix
To start you are going to need Ethereum in your Sepolia Test network address. To do this you can use this Alchemy faucet. Faucets allow you to get .5 ethereum per day to test with. The Sepolia network will be around longer than the Goerli network so use this. https://sepoliafaucet.com/
Now you are ready to start to code your contract. Once we have the front end built we will be able to access the data on this contract using the web3 framework.
This contract holds a string myCity of "Miami". That's it. The ABI will know this string is a "function" as seen in the ABI JSON. When we use the myCity().call() it will bring us "Miami" on our browser.
Below you can see the pane on the left of Remix. The deploy pane shows the environment you are connecting to "Injected Provider - Metamask".
Make sure your Metamask can see test networks and select Sepolia test network.
When it confirms you can see your contract deployed by clicking the Etherscan popup. Etherscan is an explorer where you can see all contracts on Ethereum as well as every transaction ever.
So now our contract is deployed and floating around on the Sepolia test network.
Step 2 - Build a local webserver with Express
Now we have a server. Go to your terminal and cd into the project folder and run "node server.js". Server.js is my filename.
Step 3 - Build the frontend
So the basic functionality of this example is a interface to connect to Metamask, connect to the contract and then display the contract data back on our browser.
领英推荐
To do this we need to use Web3 framework. Web3 is a popular framework that helps you connect to contracts and handle a lot of the account transfer functionality that you would expect from a blockchain project.
Put this script in your HTML head.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.2.7-rc.0/web3.min.js"></script>
Now we can build the functionality of the project on our frontend.
Connect to Metamask
// Connect Metamask
let account;
const connectMetamask = async () => {
if (window.ethereum !== "undefined") {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
account = accounts[0];
const additionalInfo = "Success! Connected to Metamask @";
document.getElementById("accountArea").innerHTML = `${additionalInfo} <br> ${account}`;
console.log("metamask wallet address connected @", account);
}
};
The end goal is to display the account address back on the browser. It requests the address from Metamask with the ethereum.request and then puts that variable onto the document in the "accountArea" ID.
Connect to Contract
//connect contract
const connectContract = async () => {
try {
//the Contract ABI
const ABI = [
[
{
"inputs": [],
"name": "myCity",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
]
];
// our contract address
const Address = "0xffcbD76ca992873BB9712576f6a0f6d28DfFB389";
window.web3 = await new Web3(window.ethereum);
window.contract = await new web3.eth.Contract(ABI, Address);
// Check if the contract is deployed
const code = await web3.eth.getCode(Address);
//this check to see if the bytecode is there, signaling that the contract is deployed
if (code.length > 2) {
console.log("Contract connected at:", Address);
document.getElementById("contractArea").innerHTML = `Success! Talking to contract @ ${Address}`;
} else {
console.error("Contract not found at the specified address.");
}
} catch (error) {
console.error("Error connecting to the contract:", error);
}
};
The end goal is to return the smart contract address off of the Ethereum blockchain and return it inside the "contractArea" ID. First we need to instantiate the contract with the smart contract address and the contract ABI (application binary interface) which is just the JSON for the contract.
Then below we actually call the address with the ABI and contract address to see if the contract has bytecode at this address.
If it has more than 2 length we know that something exists there and then we are ok to display the address back onto the browser in "contractArea".
Read data from the contract
//read data from the smart contract
const readContract = async () => {
const ABI = [
{
"inputs": [],
"name": "myCity",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"stateMutability": "view",
"type": "function"
}
];
//instantiating the contract
const contractAddress = "0xffcbD76ca992873BB9712576f6a0f6d28DfFB389";
const web3 = new Web3(window.ethereum);
const contract = new web3.eth.Contract(ABI, contractAddress);
window.contract = contract;
try {
//call the myCit function
const data = await window.contract.methods.myCity().call();
document.getElementById("dataArea").innerHTML = `The data stored on the blockchain is: ${data}`;
console.log("Data read from blockchain:", data);
} catch (error) {
console.error("Error reading data from blockchain", error);
document.getElementById("dataArea").innerHTML = error;
}
}
This last part is how we actually read the contract data from the frontend.
I had trouble with this part as it consoled me "myCity is not a function when the myCity().call() line hit.
I thought this was because the ABI said "function" under type or maybe because myCity was a string I was doing something wrong. But the real reason was because I was not instantiating the contact inside this function.
I could have used global variables but I don't think that is best practice. So I remade the address, ABI and contract object again in this readContract function.
We use .call() to get "Miami" and place it on the document at "dataArea"
const data = await window.contract.methods.myCity().call();
Then we use this in the document like this.
document.getElementById("dataArea").innerHTML = `The data stored on the blockchain is: ${data}`;
And that's pretty much it
Congratulations you just made your first smart contract on Ethereum, connected to the address on the blockchain with your frontend and you also read the data from the contract!
I left 100k oilfield to start software development at 34. This is what I want to do.
I bought bitcoin in 2017 and ever since I have been obsessed with the crypto ecosystem.
I've read about bitcoin and money, I've filmed videos on bitcoin, I've mined bitcoin on ACIS in my garage, I am building smart contracts on decentralized networks, and I'm soon graduating IT - Programming for software development in May from Nova Scotia Community College - NSCC !
I make this content here on LinkedIn to show people that it is not too late to learn what you want to learn. No one cares about what happens to you except your close friends and family. So you might as well go 110% on something that you care about.
Follow me here on LinkedIn for software development articles www.dhirubhai.net/in/justin-bishop-32276075
Or YouTube for software videos www.youtube.com/justinbishop
Cheers,
Justin
#halifax #software #blockchain #web3 #ethereum #crypto #softwaredevelopment #softwareengineer #oilandgas #careerchange
Web3 - Data Science & Analytics Marketing Specialist | Entrepreneur | Business Growth Manager | Blockchain Expert | AI, Crypto & Technology Advisor | Exponential MAU Growth Strategist | OTC Dealmaker
1 年Impressive! Looking forward to reading your article. ??